父子进程之间管道通信问题

曳尾之鱼 曳尾之鱼 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
看不懂这个程序输出的结果,求解释:


源代码:
esperantor@ubuntu:~/source$ cat noname_pipe_example.c
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

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 pipe\n");
if ((write(pipedes[1],s,13)) == -1)
{
perror("write");
exit(EXIT_FAILURE);
}
else
{
printf("the written data is :%s\n",s);
exit(EXIT_SUCCESS);
}
}
else if (pid >0)
{
sleep(2);
printf("now,read data from pipe\n");

if ((read(pipedes[0],d,13))==-1)
{
perror("read");
exit(EXIT_FAILURE);
}
printf("the data from pipe is :%s\n",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!)呢?
...全文
评论 4
收藏 已收藏
分享
返回顶部
曳尾之鱼
Linux/Unix社区 23,224 成员 74,535 内容