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

曳尾之鱼 2011-04-05 06:32:42
看不懂这个程序输出的结果,求解释:


源代码:
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!)呢?
...全文
126 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
曳尾之鱼 2011-04-05
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 guoxuqu 的回复:]

我修改了一下,现在已经正常了,修改地方我有标出
C/C++ code
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc,char **argv)
{
pid_t pid;
int temp;
int pipedes[2……
[/Quote]


有道理

调试了下,是正确的

谢谢啊
guoxuqu 2011-04-05
  • 打赏
  • 举报
回复
在栈里面s数组是存放在d数组后面,所以会打印出两个2个输入字符串(test message!)
guoxuqu 2011-04-05
  • 打赏
  • 举报
回复
因为字符串包括空结束符'\0'的长度是14,原来子进程往管道写入时没有写入空结束符,父进程从管道中读时也没有读到字符串,而printf打印字符串时是碰到空结束符才结束。
guoxuqu 2011-04-05
  • 打赏
  • 举报
回复
我修改了一下,现在已经正常了,修改地方我有标出
#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[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 pipe\n");
if ((write(pipedes[1],s,14)) == -1)//这里长度13改为14
{
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,14))==-1)//这里长度13改为14
{
perror("read");
exit(EXIT_FAILURE);
}
printf("the data from pipe is :%s\n",d);
}
return 0;
}

23,128

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧