当前位置: 技术问答>linux和unix
父子进程之间管道通信问题
来源: 互联网 发布时间:2016-11-19
本文导语: 本帖最后由 Esperantor 于 2011-04-05 18:44:07 编辑 看不懂这个程序输出的结果,求解释: 源代码: esperantor@ubuntu:~/source$ cat noname_pipe_example.c #include #include #include int main(int argc,char **argv) { pid_t pid; int temp; int pipedes[...
源代码:
esperantor@ubuntu:~/source$ cat noname_pipe_example.c
#include
#include
#include
int main(int argc,char **argv)
{
pid_t pid;
int temp;
int pipedes[2];
char s[13] = "test message!";
char d[13];
if ((pipe(pipedes))== -1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
if ((pid=fork()) == -1)
{
perror("fork");
exit(EXIT_FAILURE);
}
else if(pid==0)
{
printf("now ,write data to pipen");
if ((write(pipedes[1],s,13)) == -1)
{
perror("write");
exit(EXIT_FAILURE);
}
else
{
printf("the written data is :%sn",s);
exit(EXIT_SUCCESS);
}
}
else if (pid >0)
{
sleep(2);
printf("now,read data from pipen");
if ((read(pipedes[0],d,13))==-1)
{
perror("read");
exit(EXIT_FAILURE);
}
printf("the data from pipe is :%sn",d);
}
return 0;
}
结果:
esperantor@ubuntu:~/source$ gcc -o noname_pipe_example noname_pipe_example.c
esperantor@ubuntu:~/source$ ./noname_pipe_example
now ,write data to pipe
the written data is :test message!
now,read data from pipe
the data from pipe is :test message!test message!
怎么会输出2个输入字符串(test message!)呢?
|
我修改了一下,现在已经正常了,修改地方我有标出
#include
#include
#include
int main(int argc,char **argv)
{
pid_t pid;
int temp;
int pipedes[2];
char s[14] = "test message!";//这里数组长度应该为14,包括字符串结速符
char d[13];
if ((pipe(pipedes))== -1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
if ((pid=fork()) == -1)
{
perror("fork");
exit(EXIT_FAILURE);
}
else if(pid==0)
{
printf("now ,write data to pipen");
if ((write(pipedes[1],s,14)) == -1)//这里长度13改为14
{
perror("write");
exit(EXIT_FAILURE);
}
else
{
printf("the written data is :%sn",s);
exit(EXIT_SUCCESS);
}
}
else if (pid >0)
{
sleep(2);
printf("now,read data from pipen");
if ((read(pipedes[0],d,14))==-1)//这里长度13改为14
{
perror("read");
exit(EXIT_FAILURE);
}
printf("the data from pipe is :%sn",d);
}
return 0;
}