I am into this weird behaviour where I have my main program and a forked child. They are piped like this(the numbers are file descriptors):
___parent___
| | ____child_____
| 0 stdin | | |
| 1 pipe1[1]----------. | 1 stdout |
| 2 pipe2[1]----------.\ | 2 stderr |
|____________| \`----------> 3 pipe1[0] |
`----------> 5 pipe2[0] |
|______________|
So parent gets input from stdin but redirects stdout and stderr to two pipes. The child has closed its stdin and uses the read ends of the pipes instead.
Then I have a function to just kill the child:
void killChild(){
printf("Killing %d\n", (int)childID);
fflush(stdout);
kill(childID, SIGKILL);
waitpid(childID, NULL, 0); // getting rid of the zombie
}
The child gets succesfully killed but the problem is that the parent itself gets killed as well. I checked the PID of the child and it's correct.
So why does the parent die?
They are a collection of related processes sharing the same PGID's (Process Group ID). A common misconception is that killing the parent process will kill the children's processes too. Nevertheless, killing the parent process could allow the child processes to exist on their own.
If you are on the same terminal with the process, type ctrl-z to stop the parent, and the use ps -ef to find the PID of the php child. Use the kill lines above to effectively separate the child from the parent.
When a child process terminates, some information is returned to the parent process. When a child process terminates before the parent has called wait, the kernel retains some information about the process, such as its exit status, to enable its parent to call wait later.
Upon successful completion, fork() returns 0 to the child process and returns the process ID of the child process to the parent process. Otherwise, -1 is returned to the parent process, no child process is created, and errno is set to indicate the error.
Any attempt by the parent to write to its fd 1 or fd 2 after the child exits will result in the kernel sending SIGPIPE to the parent. The default behavior for SIGPIPE is process termination. That's probably what's happening.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With