2014-02-11 41 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;