- 論壇徽章:
- 0
|
源程序如下。
在pipeline中建立了管道,以及父子進程。在child1中的改讀管道為0號描述符,在father1中改寫管道為3號描述符。我在father1.c中先寫的順序是
printf("parent!!!");
sleep(2);
write(3, string, len);//3號對應管道文件的寫
sleep(2);
printf("parent!!!");
但為什么最終執(zhí)行pipeline的結(jié)果卻是:parent is using pipe write
child!!!parent!!!parent!!!
而不是parent!!!parent is using pipe write parent!!!
child!!!?
明明第一個printf("parent!!!");在前,然后寫管道,最后又是printf("parent!!!");結(jié)果卻是兩個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);//調(diào)用函數(shù)
exit(1);
}
void pipeline(char * pro1,char * pro2)
{
int i;
while((i = fork()) == -1);
if(i)//父
{
close(fd[0]);
close(3);//關(guān)閉3
dup(fd[1]);//把寫的管道文件描述符給3
close(fd[1]);//關(guān)閉寫的管道文件描述符
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;
} |
|