我试图理解pipe()
功能是如何工作的,我有以下程序示例理解管()函数
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);
}
我的第一个问题是,有什么好处呢,我们从关闭使用close(fd[0])
和close(fd[1])
文件描述信息在儿童和父母的过程中。第二,在父母中使用write
,父母使用read
,但是在小孩到达write
之前如果父母的处理到达read
,并且试图从没有任何东西的管子读取?谢谢!
关闭:因为最好关闭你不需要的东西。对于第二个问题:这些是潜在的阻塞功能。因此,从空管读取将阻止读者进程,直到有东西写入管道。 –
缩进时,请勿使用制表符。因为每个文字处理器/编辑器都有不同的制表位/制表符宽度设置。建议每个缩进级别使用4个空格,因为即使使用可变宽度的字体,该空间也足够宽。 – user3629249