2016-09-26 154 views
0
void execute(char **argv,int num) 
{ 
    int i; 
    pid_t pid; 
    int status; 
    int child_status; 

    if ((pid = fork()) < 0) 
    {  /* fork a child process*/ 
     printf("*** ERROR: forking child process failed\n"); 
     exit(1); 
    } 
    else if (pid == 0) 
    {   /* for the child process: */ 
     int c; 
     if (c==execvp(argv[0], argv) < 0) 
     {  /* execute the command */ 
      printf("%d\n", c); 
      printf("*** ERROR: exec failed\n"); 
      perror(" "); 
      exit(1); 
     } 
    } 
    else if(bg!=1){ 
     while (waitpid(pid,&status,WNOHANG|WUNTRACED)); 
    } 
    else if(bg==1) 
    { 
     wait (&child_status); 
     if (WIFEXITED (child_status)) 
     { 
      printf("the child process exited normally, with exit code %d\n", 
        WEXITSTATUS (child_status)); 
     } 
     else 
      printf ("the child process exited abnormally\n"); 
    } 
} 

這是我的自定義外殼程序中的執行功能。當我執行諸如gedit &之類的操作時,會在打印下一個提示之前打印退出狀態。我該如何解決? 我在做什麼錯?該過程的退出狀態在退出之前已打印

+0

你是什麼意思「打印之前」?你想要它打印後? –

+0

當子進程退出時,它應該顯示退出狀態的權利?像gedit&在後臺打開文本編輯器。當我點擊關閉該過程時,然後才顯示退出狀態。在此之前,這個過程還在繼續......好嗎? –

+0

好吧,如果有一個已經運行的gedit實例,並且你再次運行它,新實例將立即退出。許多GUI程序都這樣做,所以嘗試使用非GUI界面程序。 – redneb

回答

0

無論變量bg設置爲什麼,execute()都會阻止等待函數完成。換句話說,無論您是否想在後臺運行進程,都會得到相同的行爲。

幾點建議:

  • 當你想在後臺運行的過程,不叫waitpid函數()或wait()在執行(),而是隻返回PID。調用者將負責檢測進程何時終止。
  • 如果execute()運行前臺進程,則返回一個已知的非進程PID,如-1,以便調用者知道不要將其添加到後臺進程列表中。
  • 調用者應該在打印提示之前檢查其後臺進程列表 - 前臺進程完成或後臺進程運行後。確保這是通過非阻塞呼叫完成的。
  • 傳入bg作爲參數執行