Question
I need to fork three child process though I'm not really sure howto do that, I know how to create one, but I have no idea where togo from there.
Here is the code I have so far
int main(void)
{
pid_t pid;
pid = fork(); /* Forks a child process */
if (pid == 0)
{ /* Child Process */
/* Infinate Loop
* Prints it's PID andit's PPID(Parent PID)
* Then waits for 2seconds and repeats */
while ( pid == 0 )
{
printf("This is a child process. My PID is: %d My PPID is: %d ",getpid(), getppid());
sleep(2);
}
}
else if(pid > 0)
{ /* Parent Process */
/* Infinate Loop
* Prints it's PID
* Then waits for 1second and repeats */
while ( pid !=0 )
{ /* Infinate Loop */
printf("This is the main process. My PID is: %d ", getpid());
sleep(1);
}
}
else
{ /* fork could not be created */
fprintf(stderr, "Can't Fork.error: %d ", errno);
exit(1);
}
}
Explanation / Answer
//Hope this will help you.. #include #include #include #include #include int main(void) { pid_t pid; pid = fork(); /* Forks a child process */ ints; if (pid == 0) { /* Child Process */ /* Infinate Loop * Prints it's PIDand it's PPID(Parent PID) * Then waits for 2seconds and repeats */ printf("This is a child1 process. My PID is: %d My PPID is: %d ",getpid(), getppid()); } else if(pid > 0) { /* Parent Process */ /* Infinate Loop * Prints it'sPID * Then waits for 1second and repeats */ /* Infinate Loop*/ pid = fork(); if(pid ==0) { printf("This is a child2 process. My PID is: %d My PPID is: %d ",getpid(), getppid()); } else if(pid >0) { pid = fork(); if(pid ==0) { printf("This is a child3 process. My PID is: %d My PPID is: %d ",getpid(), getppid()); } else if(pid >0) { wait(&s); wait(&s); wait(&s); printf("This is the main process.My PID is: %d ", getpid()); } } } else { /* fork could not be created */ fprintf(stderr, "Can'tFork. error: %d ", errno); exit(1); } } /* Sample output This is a child1 process. My PID is: 15873 My PPID is: 15872 This is a child2 process. My PID is: 15874 My PPID is: 15872 This is a child3 process. My PID is: 15875 My PPID is: 15872 This is the main process.My PID is: 15872 */