我正在开发一款C语言应用程序。 父子进程通过管道进行通信。 在写入管道之前,父进程会执行其他语句。在示例代码中,我使用了sleep(10)来制造延迟。 在子进程中,它应该从管道中读取数据。 但是在子进程的读端口上没有读取到数据。
int main()
{
int pid;
FILE *fp;
fp = fopen("test.txt","w");
char *buff;
int fd[2];
int count = 0 ;
pipe(fd);
pid = fork();
if(pid == 0)
{
close(fd[1]);
ioctl(fd[0], FIONREAD, &count);
fprintf(fp,"Value of count: %d ",count);
buff = malloc(count);
fprintf(fp,"\n TIME before read: %s",__TIME__);
read(fd[0], buff, count);
fprintf(fp,"\nbuffer: %s\n TIME after read %s", buff, __TIME__);
}
else{
close(fd[0]);
sleep(10); //delay caused by application specific code replaced with sleep
write(fd[1],"THIS is it",10);
}
fclose(fp);
return 0;
}
如何使子进程等待直到数据被写入另一端?
ioctl()
,但这并不重要。如果你担心缓冲区的大小,你可以始终阻塞在单字节读取上,并在成功后吸收管道中剩余的任何内容。或者只需创建一个大型庞大的缓冲区并将其读入其中。选择最终取决于您。 - WhozCraig