LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 915|回复: 3

[solved]一个c语言程序的错误

[复制链接]
发表于 2007-12-10 20:02:31 | 显示全部楼层 |阅读模式

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <string.h>
  4. main()
  5. {
  6.         int a,lon=3;
  7.         char pbuf[]="I am your father?";
  8.         char cbuf[]="sun!";
  9.         int files[2];
  10.         if(pipe(files)==-1)
  11.         {
  12.                 perror("Failed to creat pipe!");
  13.         }
  14.         a=fork();
  15.         if(a>0)
  16.         {
  17.                 write(files[1],pbuf,strlen(pbuf)+1);
  18.         }
  19.         else
  20.                 if(a==0)
  21.                 {
  22.                         sleep(2);
  23.                         printf("%s\n",pbuf);
  24.                         lon=read(files[0],cbuf,18);
  25.                         printf("%s\n",pbuf);
  26.                 }
  27.                 else
  28.                 {
  29.                         perror("Failed to creat a childpid!");
  30.                 }
  31.         printf("pid:%d readBuffer is (%d){%s},writeBuffer is {%s}\n",getpid(),lon,cbuf,pbuf);
  32.         return 1;
  33. }
复制代码


1.ubuntu下的结果:
naiad@artist:/home/programming/OperatingSystem$ ./pipeme
pid:26252 readBuffer is (3){sun!},writeBuffer is {I am your father?}
naiad@artist:/home/programming/OperatingSystem$ I am your father?
r?
pid:26253 readBuffer is (18){I am your},writeBuffer is {r?}

2.gentoo下的结果:
naiad@artist:/home/programming/OperatingSystem$ ./pipeme
pid:26252 readBuffer is (3){sun!},writeBuffer is {I am your father?}
naiad@artist:/home/programming/OperatingSystem$ I am your father?
r?
pid:26253 readBuffer is (18){I am your father?},writeBuffer is {?}

3.Fedora下的结果:
naiad@artist:/home/programming/OperatingSystem$ ./pipeme
pid:26252 readBuffer is (3){sun!},writeBuffer is {I am your father?}
naiad@artist:/home/programming/OperatingSystem$ I am your father?
r?
pid:26253 readBuffer is (18){I am your father?},writeBuffer is {your father?}

4.我的预测:
naiad@artist:/home/programming/OperatingSystem$ ./pipeme
pid:26252 readBuffer is (3){sun!},writeBuffer is {I am your father?}
naiad@artist:/home/programming/OperatingSystem$ I am your father?
I am your father?
pid:26253 readBuffer is (18){I am },writeBuffer is {I am your fahter?}
但是我预测的结果没有出来。请老师们指点。
 楼主| 发表于 2007-12-11 17:13:09 | 显示全部楼层
这个程序好像和函数read中的第三个参数有关,小于等于7就没有问题,大于7cbuf和pbuf好像都随机的有问题。

是gcc的问题吗?
回复 支持 反对

使用道具 举报

发表于 2007-12-11 17:33:23 | 显示全部楼层
我觉得是数组越界的问题
回复 支持 反对

使用道具 举报

 楼主| 发表于 2007-12-11 18:23:51 | 显示全部楼层
原来这样--越界。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表