我使用管道和fork编写了一小段代码。子进程调用子函数写入管道,父进程调用父函数从管道中读取。
问题出现在fork()后的第一次程序调用时进入了父函数。这里关闭了写端。现在的问题是,读取调用将一些垃圾存入buf中,nread返回一个大于0的值。如何防止这种情况发生?
使用Linux 2.6.32-30-generic和gcc 4.4.3。以下是代码:
问题出现在fork()后的第一次程序调用时进入了父函数。这里关闭了写端。现在的问题是,读取调用将一些垃圾存入buf中,nread返回一个大于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);
}
'\0'
在内的6个字节)。当你收到垃圾数据时,nread
是什么?你接收到的字符串是什么? - Some programmer dude