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