作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试编写一个执行子命令的程序,并且不允许该子命令被 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 的调用,您将看到其余代码可以正常工作。
最佳答案
我必须修改这部分代码才能使其在两个平台上运行。我想这只是内核处理 session 和进程组的方式之间的差异。
if (setsid() == -1) {
#ifdef LINUX
perror("setsid error");
exit(1);
#else
if (setpgrp() == -1) {
perror("setpgrp error");
exit(1);
}
#endif
}
关于c - setpgrp/setpgid 失败(?),适用于 Mac OSX,不适用于 Linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15179361/
我是一名优秀的程序员,十分优秀!