管道?进程?不知为什么求教
源程序如下。在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;
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);
close(3);//关闭3
dup(fd);//把写的管道文件描述符给3
close(fd);//关闭写的管道文件描述符
execl(pro1,pro1,NULL);
printf("-- father1 failed.\n");
else//子
{
close(fd);
close(STD_INPUT);
dup(fd);
close(fd);
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>
intmain()
{
char output;
read(0,output,30);//0号描述符对应的是管道文件的读
printf("%s \nchild!!!",output);//读完后会有显示child!!!
return 0;
} 回复 1# 清心宁神
你的printf好多没有加\n,这样的话,print的数据会缓冲,直到\n或者程序退出才会显示,你的程序child先退出,parent后退出,所以child的printf先打印了,而parent后打印 回复 2# 羽剑天涯
谢谢指导~~
页:
[1]