2017-04-01 112 views
0

我寫了自己的shell並編寫了一個處理三重管道的函數,但是我的shell在execve後退出時遇到問題。我相信這個問題是我需要多花點時間?但我不完全確定它在哪裏,因爲這完美地執行了管道程序。在這個實現中也沒有使用等待(2),也不確定這是否與它有關。謝謝如何阻止execve退出原程序

int fd[2]; 
int fd2[2]; 

if (pipe(fd) == -1) 
{ 
    perror("ERROR CREATING PIPE"); 
    return; 
} 

pid_t pid = fork(); 

if (args4[0] != NULL) 
{ 
    switch(pid) 
    { 
     case -1: 
      printf("%s\n", "fail to fork"); 
      return; 
     case 0: 
      if (pipe(fd2) == -1) 
      { 
       perror("ERROR CREATING PIPE"); 
       return; 
      } 
      switch(pid = fork()) 
      { 
       case -1: 
        printf("%s\n", "fail to fork"); 
        return; 
        break; 
       case 0: 
        if (dup2(fd2[1], STDOUT_FILENO) == -1) 
        { 
         printf("%s\n", "fail to dup"); 
         return; 
        } 
        close(fd2[0]); 
        close(fd2[1]); 
        execve(args2[0], args2, environ); 
        exit(1); 
       default: 
        if (dup2(fd2[0], STDIN_FILENO) == -1) 
        { 
         printf("%s\n", "fail to dup"); 
         return; 
        } 
        if (dup2(fd[1], STDOUT_FILENO) == -1) 
        { 
         printf("%s\n", "fail to dup"); 
         return; 
        } 
        close(fd2[0]); 
        close(fd2[1]); 
        execve(args3[0], args3, environ); 
        exit(2); 
      } 
      exit(3); 

     default: 
      if (dup2(fd[0], STDIN_FILENO) == -1) 
      { 
       printf("%s\n", "fail to dup"); 
       return; 
      } 
      close(fd[0]); 
      close(fd[1]); 
      printf("%s\n", "4"); 
      execve(args4[0], args4, environ); 
      exit(4); 
    } 
} 
+0

您需要針對您打算調用的每個子進程進行分支。 –

+0

是的,我明白,我無法確定要分叉的過程。我認爲這將是execve(args2 [0],args2,environ),因爲它是最後一次調用的過程。我已經在所有3位高管之前嘗試過分叉,但沒有任何幫助。 – ricefieldboy

+0

沒什麼好愚蠢的。謝謝。分叉args4 – ricefieldboy

回答

0

您分叉了兩次,所以您有3個進程。它們中的每一個都被execve創建的相應進程替換。因爲execve()不會返回(成功),所以您將永遠不會到達exit()語句。這裏是你的代碼重寫,而不管道(您清楚瞭解如何設置的管道)和沒有不必要的語句:

pid_t pid = fork(); 
if (pid) { 
    execve(args4[0], args4, environ); 
} 
else { 
    pid = fork(); 
    if (pid) { 
     execve(args3[0], args3, environ); 
    } 
    else { 
     execve(args2[0], args2, environ); 
    } 
} 

看上面的重寫代碼可以更容易地看到,你會得到三個過程是這樣:

args2 [0] | args3 [0] | arg4 [0]

相關問題