简体   繁体   English

如何杀死多个子进程

[英]How to kill multiple child process

In C program simulating reader-writer problem, I have created multiple child processes using fork() and each child process called execlp() and runs another program (reader or writer) in an xterm window. 在模拟读写程序问题的C程序中,我使用fork()创建了多个子进程,每个子进程称为execlp()并在xterm窗口中运行了另一个程序(读取器或写入器)。

When I end the main() , those child running in xterm are still alive. 当我结束main() ,那些在xterm中运行的孩子仍然活着。 How do i terminate them as well? 我也该如何终止它们?

Code sample below- 下面的代码示例

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;
    }

The Group id of the parent and the child should be the same after forking so sending kill(pid,SIGTERM); 派生后父级和子级的组ID应该相同,因此发送kill(pid,SIGTERM); should take care of them ( where pid is the group Id ) 应该照顾好他们(pid是组ID)

as pointed ouf by caf in a comment bellow , kill(0, SIGTERM) will send the signal to the current process's process group 正如caf在注释行中指出的ouf一样, kill(0, SIGTERM)会将信号发送到当前进程的进程组

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

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