I've the following code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/wait.h>
#define CHILD_NO 2
#define THREAD_NO 2
int counter = 0;
void *func(void *thread_no) {
counter = counter + 1;
printf("Func: Proces ID = %d Parent process ID = %d Thread no = %d, Counter = %d \n", getpid(), getppid(), thread_no, counter);
pthread_exit(NULL);
}
int main(void) {
pthread_t threads[THREAD_NO];
int childs[CHILD_NO];
int rc, i, j;
int f = 1;
printf("Main: Proces ID = %d Parent process ID: %d\n", getpid(), getppid());
for (i = 0; i < CHILD_NO; i++) {
if (f > 0)
f = fork();
if (f == 0)
break;
else
childs[i] = f;
}
if (f == 0) {
printf("Child: Proces ID: %d Parent process ID: %d counter:%d\n" , getpid(), getppid(), counter);
/*for(j = 0; j < THREAD_NO; j++)
rc = pthread_create(&threads[j], NULL, func, (void *)j);*/
}
else{
for (i = 0; i < CHILD_NO; i++)
printf("Main: Child[%d] ID: %d created.\n", i, childs[i]);
wait(NULL);
}
pthread_exit(0);
return 0;
}
If I run it with thread part commented out I get the following output:
Main: Proces ID = 31138 Parent process ID: 28446
Child: Proces ID: 31139 Parent process ID: 31138 counter:0
Child: Proces ID: 31140 Parent process ID: 31138 counter:0
Main: Child[0] ID: 31139 created.
Main: Child[1] ID: 31140 created.
Which is expected. Parent calls fork, child process hits break and exits loop.This happens for 2 times. So we have a parent process with 2 childs. That's all. So if parent process has PID, a child will have PID+1 and another will have PID+2.
If I remove the comments and run the code I get the following:
Main: Proces ID = 31664 Parent process ID: 28446
Child: Proces ID: 31665 Parent process ID: 31664 counter:0
Child: Proces ID: 31668 Parent process ID: 31664 counter:0
Main: Child[0] ID: 31665 created.
Main: Child[1] ID: 31668 created.
Func: Proces ID = 31665 Parent process ID = 31664 Thread no = 1, Counter = 1
Func: Proces ID = 31665 Parent process ID = 31664 Thread no = 0, Counter = 2
Func: Proces ID = 31668 Parent process ID = 31664 Thread no = 1, Counter = 1
Func: Proces ID = 31668 Parent process ID = 31664 Thread no = 0, Counter = 2
Now I understand the way how threads behave. It is not their outputs that confuse me.
How and why PID of child processes differ by 3? Shouldn't the tree hierarchy of processes stay the same?