How to make child process die after parent exits?

后端 未结 24 2112
天涯浪人
天涯浪人 2020-11-22 05:31

Suppose I have a process which spawns exactly one child process. Now when the parent process exits for whatever reason (normally or abnormally, by kill, ^C, assert failure o

24条回答
  •  梦如初夏
    2020-11-22 06:25

    As other people have pointed out, relying on the parent pid to become 1 when the parent exits is non-portable. Instead of waiting for a specific parent process ID, just wait for the ID to change:

    pit_t pid = getpid();
    switch (fork())
    {
        case -1:
        {
            abort(); /* or whatever... */
        }
        default:
        {
            /* parent */
            exit(0);
        }
        case 0:
        {
            /* child */
            /* ... */
        }
    }
    
    /* Wait for parent to exit */
    while (getppid() != pid)
        ;
    

    Add a micro-sleep as desired if you don't want to poll at full speed.

    This option seems simpler to me than using a pipe or relying on signals.

提交回复
热议问题