我看到四个问题:
1) execlp()
失败了:execlp()
(或任何exec
如果成功的话,它会完全替换当前正在运行的进程映像 - 除非出现问题,否则预计不会返回。但您看到的是“孩子:睡觉完毕,正在返回”消息,因此它不可能成功。 (在你的例子中,我猜这可能是因为dmegs
本来应该dmesg
.)
2) printf()
and cout
输出缓冲意味着无法保证您按照发生的顺序获得输出。如果你想通过打印输出来调试它,你最好打印到stderr
(例如与fprintf(stderr, ...)
)(默认情况下)是无缓冲的。
3)正如其他人指出的,wait((void *)pid)
是错的。wait(NULL)
or waitpid(pid, NULL, 0)
.
4)这是否是一个问题取决于平台,但是......终止空指针参数execlp()
应明确写为(char *)0
而不仅仅是0
,以确保它作为指针而不是整数传递。一般来说,在C语言中,0
根据定义,在指针上下文中是空指针,但是当将参数传递给具有可变数量参数的函数时,编译器没有足够的信息来知道您正在尝试在指针上下文中使用它,因此将其传递为一个整数,除非你显式地转换它。在指针和整数大小不同的平台上,这可能会给您带来麻烦。
所以我认为wait()
正在工作,子进程实际上并没有运行您想要的命令,并且父进程和子进程的输出由于缓冲而变得混乱。
这是代码的稍微修改版本,它不使用任何 C++,删除了命令处理内容,并且仅通过管道输出sleep 5
to cat
(这是毫无意义的,因为sleep
无论如何都不会生成任何输出,但延迟对于查看发生的情况很有用):
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void)
{
pid_t pid;
int pfd[2];
if(pipe(pfd) == -1)
{
perror("error on pipe call");
return(1);
}
pid = fork();
if(pid == 0){//child process
fprintf(stderr, "Child: My PID = %d\n", getpid());
fprintf(stderr, "Child: Running...\n");
close(pfd[0]); //close read end of pipe
dup2(pfd[1],1);//connect the pipes
close(pfd[1]);//close extra file descriptors
fprintf(stderr, "child starting command: sleep 5\n");
execlp("sleep", "sleep", "5", (char *)0);//Load the program
fprintf(stderr, "child: execlp failed\n");
}
else
{
fprintf(stderr,"Parent: My PID = %d\n", getpid());
wait(NULL);
fprintf(stderr,"Parent: Running...\n");
close(pfd[1]); //close the write end of the pipe
dup2(pfd[0],0);//connect the pipes
close(pfd[0]); //close extra file descriptor
fprintf(stderr,"parent starting command: cat\n");
execlp("cat", "cat", (char *)0);//Load the programm
}
fprintf(stderr,"all done\n");
return 0;
}
Output:
$ gcc -Wall -o wait wait.c
$ ./wait
Child: My PID = 27846
Child: Running...
child starting command: sleep 5
Parent: My PID = 27845
(这里有5秒的延迟)
Parent: Running...
parent starting command: cat
$