- 论坛徽章:
- 0
|
源程序如下。
在pipeline中建立了管道,以及父子进程。在child1中的改读管道为0号描述符,在father1中改写管道为3号描述符。我在father1.c中先写的顺序是
printf("parent!!!");
sleep(2);
write(3, string, len);//3号对应管道文件的写
sleep(2);
printf("parent!!!");
但为什么最终执行pipeline的结果却是:parent is using pipe write
child!!!parent!!!parent!!!
而不是parent!!!parent is using pipe write parent!!!
child!!!?
明明第一个printf("parent!!!");在前,然后写管道,最后又是printf("parent!!!");结果却是两个parent!!!都在最后显示在终端上。
谢谢高手们,初学者第一次来此地非常激动呢。
/*pipeline.c*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define STD_INPUT 0
#define STD_OUTPUT 1
void pipeline(char*, char*);
int fd[2];
void main()
{
static char process1[] = "father1",process2[]="child1";
pipe(fd);//建立管道
pipeline(process1,process2);//调用函数
exit(1);
}
void pipeline(char * pro1,char * pro2)
{
int i;
while((i = fork()) == -1);
if(i)//父
{
close(fd[0]);
close(3);//关闭3
dup(fd[1]);//把写的管道文件描述符给3
close(fd[1]);//关闭写的管道文件描述符
execl(pro1,pro1,NULL);
printf("-- father1 failed.\n");
else//子
{
close(fd[1]);
close(STD_INPUT);
dup(fd[0]);
close(fd[0]);
execl(pro2,pro2,NULL);
printf("child1 failed.\n");
}
exit(2);
}
/*father1.c*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
void main()
{
static char string[] = "parent is using pipe write";
int len;
len = sizeof(string);
printf("parent!!!");
sleep(2);
write(3, string, len);//3号对应管道文件的写
sleep(2);
printf("parent!!!");
exit(0);
}
/*child1.c*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
char output[30];
read(0,output,30);//0号描述符对应的是管道文件的读
printf("%s \nchild!!!",output);//读完后会有显示child!!!
return 0;
} |
|