I am figuring out how threads with fork work and here is the code that I have tried to make some sense of. (Pardon the errors in the code)
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/wait.h>
void* f(int threadnum) {
int i;
i = fork();
if (i == 0) { // child process
printf("(%d) child says hello\n", threadnum);
} else {
printf("(%d) parent[%d] says hello\n", threadnum, i);
wait(NULL);
int new = fork();
if (new != 0){
printf("(%d) parent[%d] says hello to grandchild\n", threadnum, new);
wait(NULL);
} else
printf("(%d) grandchild says hello\n", threadnum);
}
}
int main ()
{
pthread_t pid[2];
for (int i = 0; i < 2; i++) {
pthread_create(&pid[i], NULL, f, (void *)i);
printf("Thread created with id [%li]\n", pid[i]);
}
for (int i = 0; i < 2; i++){
pthread_join(pid[i], NULL);
}
return 0;
}
And this is the output that i have gotten:
Thread created with id [663664384]
Thread created with id [655271680]
(1) parent[5690] says hello
(0) parent[5691] says hello
(1) child says hello
(1) parent[5692] says hello to grandchild
(0) child says hello
(1) grandchild says hello
(0) parent[5693] says hello to grandchild
(0) grandchild says hello
I don't see much difference as to how threads work differently from having to fork the calling of f() twice. If a single thread executes exit(), how about the whole process? If a single thread calls exec(), how about the other threads?