我有这个方法:
int build_pipe_and_call(char **argv1, std::string cmd1, char **argv2, std::string cmd2, int conc) {
std::cout << "Building Pipe...\ncmd1: " << cmd1 << "\n cmd2: " << cmd2 << "\n";
int *pipefd = new int[2];
if (pipe(pipefd) < 0) {
std::cerr << "There was an error setting up the pipe.\n";
return -1;
}
pid_t cpid1 = fork();
std::cout << "First process forked, cpid: " << cpid1 << " - Process " << getpid() << "\n";
switch (cpid1) {
case -1:
std::cerr << "There was an error forking the process.\n";
return -1;
break;
case 0: // this is the part that isn't executing
std::cout << "Dup2 return: " << dup2(pipefd[1], 1) << "\n";
std::cout << "Process " << getpid() << " duped and about to exec.\n";
execvp(cmd1.c_str(), argv1);
std::cout << "Process " << getpid() << " about to exit.\n";
_exit(0);
break;
default:
pid_t cpid2 = fork();
switch (cpid2) {
case -1:
std::cerr << "There was an error forking the process.\n";
return -1;
break;
case 0:
dup2(pipefd[0], 0);
std::cout << "Process " << getpid() << " duped and about to exec.\n";
execvp(cmd2.c_str(), argv2);
_exit(0);
break;
default:
if (conc) {
} else {
int status1, status2;
std::cout << "Process " << getpid() << " about to wait.\n";
waitpid(cpid1, &status1, 0);
waitpid(cpid2, &status2, 0);
}
break;
}
}
delete[] pipefd;
return 0;
}
我仅出于调试目的添加了打印语句。但是,当此方法运行时,这就是打印的内容。
Building Pipe...
cmd1: cat
cmd2: wc
First process forked, cpid: 1454 - Process 1453
First process forked, cpid: 0 - Process 1454
Process 1453 about to wait.
Process 1455 duped and about to exec.
进程 1454 是第一个分叉的进程,它在消息创建后立即打印该消息。但是,它从不打印来自 switch 语句的任何消息,并且从不执行指定的程序(在本例中为 cat)。该进程不会像僵尸一样徘徊,它只是消失了。结果,第二个子进程挂断了,实际上什么也没做。
(另外,补充一下,我知道我还没有添加所有适当的错误处理,功能还没有完成)。