【发布时间】: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 的调用,你会看到剩下的代码是正常的。
【问题讨论】: