Multithreaded C program; how to kill processes spawned by threads?

走远了吗. 提交于 2019-12-04 09:29:45

Create all child processes in a new process group, then send the signal to the group.

Edit:

Here's some minimal code that shows how process can change it's group and control child processes with a signal.

#include <err.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

pid_t pgid; /* process group to kill */

void terminator( int s ) /* signal handler */
{
    printf( "[%d:%d] received signal %d, exiting\n",
        getpid(), getpgrp(), s );
    exit( 1 );
}

int main() /* program entry */
{
    printf( "[%d:%d] before first fork\n",
        getpid(), getpgrp() );

    switch ( fork()) /* try with and without first fork */
    {
        case -1: err( 1, "fork" );
        case 0: break;
        default: exit( 0 );
    }

    if ( signal( SIGTERM, terminator ) == SIG_ERR )
        err( 1, "signal" );

    if ( setpgrp() < 0 ) err( 1, "setpgrp" );
    if (( pgid = getpgrp()) < 0 ) err( 1, "getpgrp" );

    printf( "[%d:%d -> %d] before second fork\n",
        getpid(), getpgrp(), pgid );

    switch ( fork())
    {
        case -1: err( 1, "fork" );
        case 0: /* child */
        {
            printf( "child [%d:%d]\n", getpid(), getpgrp());
            sleep( 20 );
            break;
        }
        default: /* parent */
        {
            printf( "parent [%d:%d]\n", getpid(), getpgrp());
            sleep( 5 );
            killpg( pgid, SIGTERM );
            sleep( 20 );
        }
    }

    printf( "[%d:%d] exiting\n", getpid(), getpgrp());
    exit( 1 );
}

  1. Create all child processes in a new process group, then send the signal to the group. (thanks Nokolai)
  2. Keep records on all processes created and use that to signal them when desired.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!