Hi everyone!
I'm writing some code in C under UNIX, which should give some output like this:
PARENT: pid = 10063
CHILD: my pid = 10064
CHILD: my parent's pid = 10063
CHILD: Sleeping...
PARENT: my child's pid = 10064
PARENT: Waiting for the child to exit...
CHILD: Done sleeping...
PARENT: child is dead.
The output I am getting looks like this:
CHILD: my pid = 3891
CHILD: my parent's pid = 3890
PARENT: my pid = 3890
PARENT: my child's pid = 3891
PARENT: Waiting for the child to exit...PARENT: the child is dead.
loki.brunel.ac. uk% CHILD: Sleeping...CHIL D: Done sleeping...
Here is the code I have done:
What is wrong here, why it goes to the parent process in the middle of the childs process commands? How do I change this?
I'm writing some code in C under UNIX, which should give some output like this:
PARENT: pid = 10063
CHILD: my pid = 10064
CHILD: my parent's pid = 10063
CHILD: Sleeping...
PARENT: my child's pid = 10064
PARENT: Waiting for the child to exit...
CHILD: Done sleeping...
PARENT: child is dead.
The output I am getting looks like this:
CHILD: my pid = 3891
CHILD: my parent's pid = 3890
PARENT: my pid = 3890
PARENT: my child's pid = 3891
PARENT: Waiting for the child to exit...PARENT: the child is dead.
loki.brunel.ac. uk% CHILD: Sleeping...CHIL D: Done sleeping...
Here is the code I have done:
Code:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(){
pid_t pid;
switch (pid = fork())
{
case -1:
perror("couldn't fork");
break;
case 0:
printf("CHILD: my pid = %d\n", getpid());
printf("CHILD: my parent's pid = %d\n",getppid());
printf("CHILD: Sleeping...");
sleep(10);
printf("CHILD: Done sleeping...");
break;
default:
printf("PARENT: my pid = %d\n", getpid());
printf("PARENT: my child's pid = %d\n", pid);
printf("PARENT: Waiting for the child to exit...");
waitpid(pid);
printf("PARENT: the child is dead.\n");
break;
}
return 0;
}
What is wrong here, why it goes to the parent process in the middle of the childs process commands? How do I change this?
Comment