2017-03-04 41 views
-1

對於Unix類,我們必須使用fork(),pipe(),exec()重新創建管道重定向功能的外殼|。我能夠這樣做,但我們現在必須在循環中實現整個程序,以便一旦用戶完成,他們可以再次執行。我該如何回到節目的開始?問題在於exec()系統調用完全取代了當前正在運行的可執行文件。我如何在我的程序中返回main()?如何在使用exec()系統調用後回到main()?

#include <iostream> 
#include <unistd.h> 
#include <string> 
#include <cstring> 
#include <sys/types.h> 
#include <sys/wait.h> 


using std::cout; 
using std::cin; 
using std::endl; 
using std::string; 

int main (int argc, char* argv[]) { 

    char command1[127]; 
    char command2[127]; 

    char* token1[5]; 
    char* token2[5]; 

    int pipefd[2], 
     i = 0; 

    pid_t rs, fs; 

    // Get two commands from users. 

    cout << "Enter command 1 along with any arguments: "; 
    cin.getline(command1, 127); 

    string comString1 = command1; 
    if (comString1 == "quit") 
     exit(1); 

    cout << "Enter command 2 along with any arguments: "; 
    cin.getline(command2, 127); 

    string comString2 = command2; 
    if (comString2 == "quit") 
     exit(1); 

    // Parse both commands into tokens. 

    token1[i] = strtok(command1, " "); 
    while (token1[i] != NULL) { 
     i++; 
     token1[i] = strtok(NULL, " "); 
    } 

    i = 0; 

    token2[i] = strtok(command2, " "); 
    while (token2[i] != NULL) { 
     i++; 
     token2[i] = strtok(NULL, " "); 
    } 

    // Create pipe. 

    rs = pipe(pipefd); 

    if (rs < 0) { 
     perror("pipe"); 
     exit(1); 
    } 

    // First fork. There are now two processes. 

    rs = fork(); 

    if (rs < 0) { 
     perror("fork"); 
     exit(1); 
    } 

    if (rs == 0) { // Child 
     close(pipefd[1]); 

     close(0); 

     dup(pipefd[0]); 

     close(pipefd[0]); 

     // Second fork. There are now three processes. 

     fs = fork(); 

     // Trouble begins here I reckon. I forked once and forked again in a child. That may be an issue here. 

     if (fs == 0) { Child 
      rs = execlp(token2[0], token2[0], token2[1], token2[2], token2[3], token2[4], NULL); 
      if (rs < 0) { 
       perror("execlp in child"); 
       exit(1); 
      } 
     } 
     else { // Parent 
      // This execl() functions runs, but runs over and over. Am I infinitely forking processes and thus calling execl() infinitely? 
      execl("/home/hopper/z1806979/csci330/Assign4/Assign4", "Assign4", NULL); 
     } 
    } 
    else { // Parent 

     close(pipefd[0]); 

     close(1); 

     dup(pipefd[1]); 

     close(pipefd[1]); 

     rs = execlp(token1[0], token1[0], token1[1], token1[2], token1[3], token1[4], NULL); 

     if (rs < 0) { 
      perror("execlp in parent"); 
      exit(1); 
     } 
    } 

    return 0; 
} 
+0

1)不要發送垃圾郵件標籤!這不是C實現的。2)學習[問]。 – Olaf

+0

感謝您的輸入。我刪除了c標誌。 –

+1

1)這是一個_tag_ 2)不,我已經刪除它。 3)專注於改善問題。 – Olaf

回答

0

exec是一個系統調用恢復當前進程調用exec與包含在指定的文件中的代碼的當前代碼。我懷疑你自己不斷恢復代碼,並且你正在使用一些輸入命令(不應該是)來恢復你的「shell」。

你也應該注意到,恢復後沒有辦法回到以前的代碼中......恢復,恢復。