Я следующий код, который создает определенное количество дочерних потоков с использованием fork()
:вилка() Детские цепи
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#define NUM_THREADS 4
int main()
{
int i;
pid_t pid;
for(i = 0; i < NUM_THREADS; i++){ //Do this equal to the number of threads
pid = fork();//Use this to avoid multiple forking
if(pid == 0){ //If it's a child process
printf("Hello World! Greetings from PID: %ld! :D\n", (long)getpid()); //getpid returns the pid of the process
exit(0); //Exit the process
}else if(pid == -1){
printf("Oh no! Could not fork! :(Exiting!\n");
return 0;
}
}
int status;
for(i = 0; i < NUM_THREADS; i++){
wait(&status);//wait until all the children processes have finished.
}
printf("All done! I am the parent process! My PID is: %ld if you were curious! \n", (long)getpid());
return 0;
}
Это был предоставлен нам в качестве примера. Его выход похож:
Hello World! Привет от PID: 118358! : D
Hello World! Привет от PID: 118359! : D
Hello World! Привет от PID: 118360! : D
Hello World! Привет от PID: 118362! : D
Что бы я хотел сделать, вместо того, чтобы иметь один родительский процесс с большим количеством детей, состоит в том, чтобы родительский элемент создавал дочерний процесс, который создает дочерний процесс и т. Д. Для определенного числа потоки. Как я могу это сделать?
Вы пытались закодировать это самостоятельно? С чем вы столкнулись? – davmac