0
我試圖編寫一個程序來執行一個子命令,並且不允許該子項被Ctrl + C殺死。setpgrp/setpgid失敗(?),適用於Mac OSX,不適用於Linux
我讀過,我可以用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的調用,您將看到其餘代碼正常工作。
**只是一個FYI **'setsid()'成功的OS X後,沒有根在一個子進程完全fork後。基本上'vfork'複製了一些東西,但流程環境結構在兩者之間共享(幾乎就像一個進程和一個線程之間的混合)......它意味着fork/exec產卵的速度更快,其中複製環境是浪費精力。 (爲什麼是的,我們確實在大學的MINUX 2中實現了'vfork',感謝提問;)) – Barry 2016-04-14 01:00:58