2

I'm writing a program in C. The program does fork() once when it starts. What's the best way to let child process die on its own when the parent process exits (without parent killing child process explicitly)?

For example, if I send a SIGTERM to the parent process, the child doesn't exit.

woodings
  • 7,503
  • 5
  • 34
  • 52

1 Answers1

1

You can set up a signal handler, and send a signal to the child process from the parent when the parent reaches the end of its execution. The fork function returns the process id of the child to the parent, so this can be supplied to the kill function. You can pass it SIGINT or SIGTERM or the signal of your 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;

}

rurouniwallace
  • 2,027
  • 6
  • 25
  • 47