hello every one I want to ask a question about forking
here is the code
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#define MAX_COUNT 5
#define BUF_SIZE 100
void main(void)
{
pid_t pid;
int i;
char buf[BUF_SIZE];
fork();
pid = getpid();
for (i = 1; i <= MAX_COUNT; i++) {
sprintf(buf, "This line is from pid %d, value = %d\n", pid, i);
write(1, buf, strlen(buf));
}
printf("child id :%d\n" , pid);
printf("parent id :%d\n" , getppid());
}
and when i run it here is the output
This line is from pid 31130, value = 1
This line is from pid 31130, value = 2
This line is from pid 31130, value = 3
This line is from pid 31130, value = 4
This line is from pid 31130, value = 5
child id :31130
This line is from pid 31131, value = 1
parent id :31052
This line is from pid 31131, value = 2
This line is from pid 31131, value = 3
This line is from pid 31131, value = 4
This line is from pid 31131, value = 5
child id :31131
parent id:31130
it really confused me why
-
the line parent id and child id printed two times
-
why child id value is different both time when i have called for
only once -
why the second time parent id value is equal to first one child id value
what is actually the parent and chile Id thanks alot
following is the answers of your questions:
When you create a process fork it actually starts one another process
hence after forking everything is executed by the main process as well as the child process so the line parent id and child id printed twice and it given different values both the time because both are executed by different processes so both have different id and different parent id now the answer of your third question is at that time of execution the second process executing the statement so its parent is the previous process so the second time parent id value is equal to first one child id value.
I hope you would be able to understand it.