Reputation: 95
I'm not sure what does this code do.
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
int main(void)
{
for(int i=0; i<2; i++)
{
int pid=fork();
if(pid==0)
{
printf("child process \n");
printf("Child pid id [%d], parent pid is [%d]\n", (int) getpid(), (int) getppid());
} else if(pid>0)
{
int stats;
wait(&stats);
printf("parent process \n");
printf("Child pid id [%d], parent pid is [%d]\n", (int) getpid(), (int) getppid());
}
}
return 0;
}
I call fork()
and assign it's value to variabe pid
. Then we go to int stats
, next line returns pid=0
, then the program displays child process and then the parent process. It works pretty nice, but only when i<1
. I thought that it is possible to do the same thing once again, but it's strange. fork()
creates a new child process, so if it is used only once, if should create a child process, which parent is an IDE. Why am I wrong and what should I change to make 2 parents and 1 child for each, basically 4 processes?
Upvotes: 0
Views: 235
Reputation: 26196
I am not completely sure what you mean by "2 parents". In any case, you need to return the child so that they do not loop again:
printf("Child pid id [%d], parent pid is [%d]\n", (int) getpid(), (int) getppid());
return 0;
Otherwise you will have the children spawning other processes.
Upvotes: 1