【发布时间】:2012-03-26 17:32:20
【问题描述】:
我使用管道和叉子编写了一个小代码。子进程调用写入管道的子函数。父进程调用从管道读取的父函数。
当 fork() 之后程序的第一次调用转到父函数时,问题就出现了。这里写端是关闭的。现在的问题是 read 调用正在将一些垃圾读入 buf 而 nread 给出的 value > 0 。如何防止这种情况发生。
使用 Linux 2.6.32-30-generic 和 gcc 4.4.3。下面是代码::
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#define MSGSIZE 16
void parent(int* p);
void child(int* p);
char* msg1 = "hello";
char* msg2 = "bye";
int main()
{
int pfd[2];
if(pipe(pfd) == -1)
{
printf("Unable to create pipe\n");
exit(1);
}
fcntl(pfd[0],F_SETFL,O_NDELAY);
if(fork() == 0)
child(pfd);
else
parent(pfd);
return 0;
}
void parent(int p[2])
{
int nread;
char buf[MSGSIZE];
buf[0] = '\0';
close(p[1]);
for(;;)
{
nread = read(p[0] , buf , MSGSIZE);
if(nread == 0)
{
printf("pipe Empty/n");
sleep(1);
}
else
{
if(strcmp(buf,msg2) == 0)
{
printf("End of conversation\n");
exit(0);
}
else
printf("MSG=%s\n" , buf);
}
}
}
void child(int p[2])
{
int count;
close(p[0]);
for(count = 0 ; count < 3 ; count++)
{
write(p[1],msg1 , MSGSIZE);
sleep(3);
}
write(p[1],msg2,MSGSIZE);
exit(0);
}
【问题讨论】:
-
您正在向管道写入 16 个字节,但字符串只有 5 个字节(6 个以
'\0'结尾)。当你收到垃圾时,nread是什么?你收到的字符串是什么?