[英]setpgrp/setpgid fails (?), works on Mac OSX, not on Linux
I'm trying to write a program that executes a child command, and does not allow that child to be killed by Ctrl+C. 我正在尝试编写一个执行子命令的程序,不允许该子被Ctrl + C杀死。
I've read that I can accomplish this with setpgid/setpgrp. 我读过我可以使用setpgid / setpgrp完成此操作。
The following code works on OSX, but on Linux (2.6.32, Ubuntu 10.04) running something like, 以下代码在OSX上有效,但在运行以下命令的Linux(2.6.32,Ubuntu 10.04)上,
./a.out ls
causes no output to occur and the program cannot be killed with SIGINT. 导致不发生任何输出,并且无法使用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);
}
If you comment out the call to setpgrp, you will see that the remaining code is functional. 如果注释掉对setpgrp的调用,您将看到其余代码正常运行。
I had to modify this section of the code for it to work on both platforms. 我必须修改代码的这一部分,才能在两种平台上都可以使用。 I guess this is simply a difference between how the kernels treat sessions and process groups. 我想这只是内核如何处理会话和进程组之间的区别。
if (setsid() == -1) {
#ifdef LINUX
perror("setsid error");
exit(1);
#else
if (setpgrp() == -1) {
perror("setpgrp error");
exit(1);
}
#endif
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.