c - Linux: exit forked child process when parent exits -
this question has answer here:
- how make child process die after parent exits? 22 answers
- best way kill child processes 29 answers
i'm writing program in c. program fork()
once when starts. what's best way let child process die on own when parent process exits (without parent killing child process explicitly)?
for example, if send sigterm parent process, child doesn't exit.
you can set signal handler, , send signal child process parent when parent reaches end of execution. fork
function returns process id of child parent, can supplied kill
function. can pass sigint
or sigterm
or signal of choosing.
#include <signal.h> #include <stdio.h> #include <unistd.h> int main( int argc, char* argv[] ) { pid_t id = 0; id = fork(); if( id == 0 ) { /*child code*/ } else if( id == -1 ) { printf( "error forking." ); } else { /*parent code*/ kill( id, sigint ); } return 0;
}
Comments
Post a Comment