繁体   English   中英

如何杀死多个子进程

[英]How to kill multiple child process

在模拟读写程序问题的C程序中,我使用fork()创建了多个子进程,每个子进程称为execlp()并在xterm窗口中运行了另一个程序(读取器或写入器)。

当我结束main() ,那些在xterm中运行的孩子仍然活着。 我也该如何终止它们?

下面的代码示例

main() {
    while(1) {
    scanf(choice);
    switch(choice) {
        case 1: 
            reader()
            break;
        case 2: 
            writer();
            break;
        default:
            kill(getpgid(getpid()), SIGTERM); // killing the group id
            return 0;
        }
    }

reader() {
    /*
    some semaphore manipulation
    */
    execlp("xterm", "xterm", "-e", "./read", NULL);
    /*
    some semaphore manipulation
    */
    return 0;
    }

writer() {
    /*
    some semaphore manipulation
    */
    execlp("xterm", "xterm", "-e", "./write", NULL);
    /*
    some semaphore manipulation
    */
    return 0;
    }

派生后父级和子级的组ID应该相同,因此发送kill(pid,SIGTERM); 应该照顾好他们(pid是组ID)

正如caf在注释行中指出的ouf一样, kill(0, SIGTERM)会将信号发送到当前进程的进程组

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM