gpt4 book ai didi

c - 子进程如何在读取第一条消息后不离开while循环?

转载 作者:行者123 更新时间:2023-11-30 19:34:09 25 4
gpt4 key购买 nike

我最近在尝试解决 Linux C 中我自己的管道问题时遇到了这个例子,它确实回答了我的问题,但给了我另一个问题,为什么子进程在第一条消息之后不离开 while 循环?如果它已经读取完输入消息,那么它不是在父进程有机会在 sleep(5) 之后输入第二条消息之前就离开吗?

    #include <stdio.h>
#include <unistd.h>
#include <sys/ioctl.h>

int main()
{
int pid = 0;

// create pipe pair
int fd[2];
pipe(fd);

pid = fork();
if (pid == 0)
{
// child side
char *buff = NULL;
char byte = 0;
int count = 0;

// close write side. don't need it.
close(fd[1]);

// read at least one byte from the pipe.
while (read(fd[0], &byte, 1) == 1)
{
if (ioctl(fd[0], FIONREAD, &count) != -1)
{
fprintf(stdout,"Child: count = %d\n",count);

// allocate space for the byte we just read + the rest
// of whatever is on the pipe.
buff = malloc(count+1);
buff[0] = byte;
if (read(fd[0], buff+1, count) == count)
fprintf(stdout,"Child: received \"%s\"\n", buff);
free(buff);
}
else
{ // could not read in-size
perror("Failed to read input size.");
}
}

// close our side
close(fd[0]);
fprintf(stdout,"Child: Shutting down.\n");
}
else
{ // close read size. don't need it.
const char msg1[] = "Message From Parent";
const char msg2[] = "Another Message From Parent";
close(fd[0]);
fprintf(stdout, "Parent: sending \"%s\"\n", msg1);
write(fd[1], msg1, sizeof(msg1));
sleep(5); // simulate process wait
fprintf(stdout, "Parent: sending \"%s\"\n", msg2);
write(fd[1], msg2, sizeof(msg2));
close(fd[1]);
fprintf(stdout,"Parent: Shutting down.\n");
}
return 0;
}

最佳答案

如果没有可用数据,

read 将阻塞直到数据到达(除非管道设为非阻塞)。

关于c - 子进程如何在读取第一条消息后不离开while循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44313786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com