Hello Sir, thanks for the course, this is very useful.
This is from one of the exercises on unix, given the below code:
int main(){
printf(“%d\n”, getpid());
switch(fork()){
case -1:
printf(“Error creating process!!”);
case 0:
printf(“%d\n”, getpid());
setpgrp();
close(0);
close(1);
close(2);
break;
default:
exit(0);
}
while(1){
}
}
I tried running it a couple of times and was trying to get parent to receive 0 and exit before the child could make itself the process group owner and create its own kingdom. is this even possible? In the above program can the following condition ever occur? (I understand something is not letting this happen and would like to get some clarity about this)
Thanks in Advance!
Yes, the parent can terminate before the child calls setpgrp(). But the child is not killed because the parent has not yet sent SIG_KILL signal to the child ( or to the family of processes ). Note that the purpose of setpgrp() is exactly to remove self ( in this case, the child, ) from the process group of the parent so that a group signal from the parent process ( via a kill() system call ) does not terminate the child. I have never come across a situation where the child gets killed before it has even started to run child code. If you were to insert a kill() system call with appropriate parameters before the exit() call in the parent code, the situation you describe may occur. Simple death of a process does not kill its child processes.
Note the following : (1) case Zero: is the code executed only by the child.
(2) default: code in the switch is executed only by the parent ( i.e. self )
(3) exit (n) ==> sends the exit code to parent of self and NOT the child. Parent should execute wait ( &code ) call to receive exit code
of the child. That wait call will return if and only when the child executes exit ( n ) system call.
In your code, there is no question of racing. The current process simply creates a child and does exit. After that, only the child process continues to run.
Please login first to submit.