【问题标题】:setpgrp/setpgid fails (?), works on Mac OSX, not on Linuxsetpgrp/setpgid 失败(?),适用于 Mac OSX,不适用于 Linux
【发布时间】:2013-03-02 20:56:30
【问题描述】:

我正在尝试编写一个执行子命令的程序,并且不允许该子命令被 Ctrl+C 杀死。

我读到我可以使用 setpgid/setpgrp 完成此操作。

以下代码适用于 OSX,但在 Linux(2.6.32,Ubuntu 10.04)上运行类似,

./a.out ls

导致不发生输出,并且无法使用 SIGINT 终止程序。

#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>

int main(int argc, char **argv) {
    if (argc < 2) {
        printf("Please provide a command\n");
        exit(1);
    }

    int child_pid = vfork();

    if (child_pid == 0) {
        if (setpgrp() == -1) {
            perror("setpgrp error");
            exit(1);
        }

        printf("Now executing the command:\n");

        argv++;
        if (execvp(argv[0], argv) == -1) {
            perror("Could not execute the command");
            exit(1);
        }
    }

    int child_status;
    wait(&child_status);
}

如果你注释掉对 setpgrp 的调用,你会看到剩下的代码是正常的。

【问题讨论】:

    标签: c fork kill sigint


    【解决方案1】:

    我必须修改这部分代码才能在两个平台上工作。我想这只是内核处理会话和进程组的方式之间的区别。

    if (setsid() == -1) {
       #ifdef LINUX
       perror("setsid error");
       exit(1);
       #else
       if (setpgrp() == -1) {
           perror("setpgrp error");
           exit(1);
       }   
       #endif
    }   
    

    【讨论】:

    • 仅供参考setsid() 在完整的fork 之后在子进程中没有root 的情况下在OS X 上成功。基本上vfork 复制了一些东西,但是进程环境结构在两者之间共享(几乎就像进程和线程之间的混合体)......这意味着 fork/exec 产生更快,复制环境是浪费精力. (为什么是的,我们确实在大学的 MINUX 2 中实现了vfork,感谢您的提问。;)
    猜你喜欢
    • 1970-01-01
    • 2018-02-23
    • 2017-08-20
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    相关资源
    最近更新 更多