我正在用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;
}
Run Code Online (Sandbox Code Playgroud)
如何使子进程等到数据写入另一端?