0

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

4

1 回答 1

1

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

if (setsid() == -1) {
   #ifdef LINUX
   perror("setsid error");
   exit(1);
   #else
   if (setpgrp() == -1) {
       perror("setpgrp error");
       exit(1);
   }   
   #endif
}   
于 2013-03-06T06:03:17.047 回答