Reputation: 391
Say I create a pipe between child and parent process and the child process ends normally, will child process's pipes been closed automatically?
Also, If the child process also has a child process and the child process ends with a segmentation fault, will it also kill my grandchild process? I mean remove it from the process table(I don't need to wait for it).
EDIT: For example for the following code I generate a segmentation fault in the child process and try to wait for it in the parent process. After I run the program, waitpid return -1, but when I check WIFEXITED(status) it seems like the child process program exit normally. And I got a
Killing child process failed: No such process
error try to kill my grandchild process. I wonder if this is because segmentation fault automatically close both child and grandchild process?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
int main( void ) {
pid_t childpid;
int ends[ 2 ];
pipe( ends );
if ( ( childpid = fork() ) == -1 ) {
perror( "fork failed" );
exit( 0 );
}
if( childpid == 0 ) {
pid_t cpid;
if ( ( cpid = fork() ) == -1 ) {
perror( "fork failed" );
exit( 0 );
}
if ( cpid == 0 ){
while(1);
}
else{
printf("cpid is : %d\n",cpid);
char msg[32];
sprintf( msg, "%d", cpid );
printf("cpid con is : %s\n", msg);
if( write( ends[ 1 ], msg, 32 ) == -1 ) {
perror( "Write failed" );
exit( 0 );
}
char *s = NULL;
*s = 15;
while(1);
}
}
else{
printf("childpid is : %d\n",childpid);
char msg[ 32 ];
int cpid;
if( read( ends[0], msg,32 ) == -1 ) {
perror("read failed");
exit( 0 );
}
cpid = atoi( msg );
int status;
while(1) {
if ( waitpid( childpid, &status, WNOHANG ) == -1 ) {
//printf( "%d\n", WIFEXITED(status) );
if ( kill( cpid, 9 ) == -1 ) {
perror( "Killing child process failed" );
exit( 0 );
}
/*if ( kill( cpid, 9 ) == -1 ) {
perror( "Killing child process failed" );
exit( 0 );
}*/
}
}
}
return 0;
}
Upvotes: 3
Views: 5036
Reputation: 60056
The OS will close all the filedescriptors associated with the process that has died or exited. If that closes the last filedescriptor pointing to a pipe's read end, then writes to the write end will start generating SIGPIPEs (fds are ref-counted references to vnode entity behind them).
If a parent dies, its child will be reparented to init
. init
will wait on it. (Grandparents can't wait
on grandchildren anyhow).
Upvotes: 8