2014-02-11 148 views
1

標題不言而喻。這裏的功能:如何等待子進程結束

void fork_and_chain(int * pipein, int * pipeout, Command *cmd, int size) 
{ 
    auto pid = fork(); 
    int status; 

    if(!pid) 
    { 
     if(pipein) { 
      dup2(pipein[0], 0); 
      close(pipein[0]); 
      close(pipein[1]); 
     } else if (cmd->redirectin) { 
      int fin = open(cmd->filename.c_str(), O_RDONLY); 
      dup2(fin, 0); 
      close(fin); 
     } 

     if(pipeout) { 
      dup2(pipeout[1], 1); 
      close(pipeout[0]); 
      close(pipeout[1]); 
     } else if (cmd->redirectout) { 
      int fout = open(cmd->filename.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR); 
      dup2(fout, 1); 
      close(fout); 
     } 

     if (execvp(cmd->args_char[0], cmd->args_char.data()) < 0) { 
      std::cerr << "Command not Found" << std::endl; 
     } 
    } else if (pid < 0) { 
     std::cerr << "Fork failed." << std::endl; 
     exit(1); 
    } else { 
     // waiting for child process to finish 
    } 
} 

無論我放在那裏我得到一個無限循環(我正在做一個殼)。我要麼無限地獲得「cmd」提示,要麼完全沒有。鏈接代碼繼續運行,我不知道終止它。

回答

1

我想你在尋找waitpid()。在您的評論部分添加:

int status = 0; 
waitpid(pid, &status, 0); 
std::cerr << "child finished with status: " << status << std::endl;