我试着做三个过程来互相管道。然而,我真的对第三个过程感到困惑。分叉和管道--只有两个进程--没有问题。当我添加+1循环来测试第三个进程是否产生时,我在终端中得到了奇怪的结果。
这是我的代码(有奇怪的结果):
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(){
int status, i;
int pip[2];
/* Spawn 3 subprocesses and pipe the first 2*/
for (i=0; i<3; i++){
if (i==0) pipe(pip);
if (fork()==0){
/* First subprocess */
if (i==0){
dup2(pip[1], 1); //pip[0] will replace stdout
close(pip[0]);
if (execlp("ls", "ls", NULL)) perror("process1");
}
/* Second subprocess */
if (i==1){
dup2(pip[0], 0); //pip[1] -> will replace stdin
close(pip[1]);
if (execlp("more", "more", NULL)) perror("process2");
}
/* Third subprocess */
if (i==2){
close(pip[0]); //reseting fd
close(pip[1]); //reseting fd
open(0); //reseting fd
open(1); //reseting fd
if (execlp("ls", "ls", NULL)) perror("process3");
}
}
}
wait(&status);
return 0;
}将for循环改为2循环而不是3循环停止了奇怪的行为。奇怪的是,随机地,我会在终端中得到其中一个输出:
manos@megistanas:~/Desktop/test$ ./test
test test2.c test3.c test4.c test.5c test.c
test
test2.c
test3.c
test4.c
test.5c
test.c
manos@megistanas:~/Desktop/test$在这种情况下,它正常工作。在某些情况下,情况是这样的:
manos@megistanas:~/Desktop/test$ test
test2.c
test3.c
test4.c
test.5c
test.c
test test2.c test3.c test4.c test.5c test.c
manos@megistanas:~/Desktop/test$ manos@megistanas:~/Desktop/test$ manos@megistanas:~/Desktop/test$ manos@megistanas:~/Desktop/test$ manos@megistanas:~/Desktop/test$点击回车时,只写提示符,等待更多的输入。第三个奇怪的行为是:
manos@megistanas:~/Desktop/test$ test
test2.c
test3.c
test4.c
test.5c
test.c
(blinking prompt symbol)一旦我点击enter程序就正常结束了。有人能解释一下发生了什么吗?
发布于 2011-10-23 01:07:26
开放(0); 开放(1);
请阅读手册页以打开(2)。
提示:它不接受一个参数。您可能应该使用-Wall进行构建,并注意编译器警告。
这可能并不能完全解释你看到了什么,但是考虑到这个明显的错误,我太懒了,再也看不下去了。
https://stackoverflow.com/questions/7863594
复制相似问题