setpgrp / setpgid失败(?),适用于Mac OSX,不适用于Linux

时间:2013-03-02 20:56:30

标签: c fork kill sigint

我正在尝试编写一个执行子命令的程序,并且不允许该孩子被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的调用,您将看到其余代码正常运行。

1 个答案:

答案 0 :(得分:1)

我必须修改代码的这一部分才能在两个平台上运行。我想这只是内核处理会话和进程组的区别。

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