【发布时间】:2015-08-08 18:59:50
【问题描述】:
我正在学习进程间通信,并遇到了下面的示例程序。
我不明白是什么阻止了父进程在子进程完成 write 之前尝试 read(作为程序底部 else 条件的一部分) .
什么(如果有的话)限制父进程在子进程写入标准输出之前尝试从标准输入读取?
int main(void)
{
int fd[2], nbytes;
pid_t childpid;
char string[] = "Hello, world!\n";
char readbuffer[80];
pipe(fd);
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
/* Send "string" through the output side of pipe */
write(fd[1], string, (strlen(string)+1));
exit(0);
}
else
{
/* Parent process closes up output side of pipe */
close(fd[1]);
/* Read in a string from the pipe */
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
}
return(0);
}
【问题讨论】:
-
在调用系统函数'pipe()'时,始终检查返回值以确保操作成功。成功时 pipe() 返回 0 失败时 pipe() 返回 -1 并设置 'errno'
-
关于关闭管端的cmets是向后的
-
'read()' 函数不会将字符串终止符字节 '\0' 附加到读取的字符串,因此对 printf() 的立即调用(可能)将失败。取决于首先发生的是 read() 还是 write(),读取可能会在没有读取所有数据字节的情况下返回。读取应该在一个循环中,同时检查/累积返回的字节数。当返回的字节数为 0 时,使用累积的字节数终止字符串,(可能没有必要,因为子进程发送终止字节,但这是一个好习惯)如果返回的值曾经
-
@user3629249:
read()调用将读取write()调用包含在管道上发送的数据中的空字节。写入的长度为strlen() + 1以包含空字节。
标签: c process pipe fork parent-child