2013-03-02 142 views
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的調用,您將看到其餘代碼正常工作。

回答

1

我不得不修改代碼的這一部分,以使它可以在兩個平臺上工作。我想這只是內核如何處理會話和進程組的差異。

if (setsid() == -1) { 
    #ifdef LINUX 
    perror("setsid error"); 
    exit(1); 
    #else 
    if (setpgrp() == -1) { 
     perror("setpgrp error"); 
     exit(1); 
    } 
    #endif 
} 
+0

**只是一個FYI **'setsid()'成功的OS X後,沒有根在一個子進程完全fork後。基本上'vfork'複製了一些東西,但流程環境結構在兩者之間共享(幾乎就像一個進程和一個線程之間的混合)......它意味着fork/exec產卵的速度更快,其中複製環境是浪費精力。 (爲什麼是的,我們確實在大學的MINUX 2中實現了'vfork',感謝提問;)) – Barry 2016-04-14 01:00:58

相關問題