【问题标题】:How to kill multiple child process如何杀死多个子进程
【发布时间】:2012-08-15 16:16:46
【问题描述】:

在模拟读写器问题的 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;
    }

【问题讨论】:

    标签: c kill-process


    【解决方案1】:

    fork 后父子组 id 应该相同,所以发送kill(pid,SIGTERM); 应该照顾他们(其中 pid 是组 ID)

    正如 caf 在下面的评论中指出的那样,kill(0, SIGTERM) 将向当前进程的进程组发送信号

    【讨论】:

    • 如何确定组id?
    • 使用 getpgid() ,更多细节可在此处获得 (linux.die.net/man/3/getpgid) 希望对您有所帮助
    • 我已经完成了“kill(getpgid(getpid()),SIGTERM);”但是 xterm 窗口仍然打开,我仍然可以继续处理它们。
    • 您的 execlp () 调用是什么样的? (一个更简单的解决方案是在创建时将您的子 ID 列表保留在父级中,然后通过它循环并杀死每一个。
    • 您也可能想在这里的第一个示例 (docstore.mik.ua/orelly/unix3/upt/ch24_22.htm) 看看它如何适用于您的案例
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 2014-10-22
    • 1970-01-01
    相关资源
    最近更新 更多