小编jir*_*lav的帖子

C - 如何在只读取单个字符时检测管道中的EOF?

正如回答中所解释的那样,在编写进程关闭所有相关文件描述符EOF之后,我期待读者进程能够正确捕获.

但这并没有发生,这个程序最终陷入无休止的循环.父母等待孩子完成,孩子等待发出EOF封闭管道的信号.

为什么读者进程没有收到EOF

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <wait.h>

#define STRING_TO_SEND "Hello, world!\n"

int main() {
    int fd[2], i = 0;
    __pid_t pid;
    char _char;
    ssize_t nbytes;

    pipe(fd);
    pid = fork();

    if (pid == -1) {
        // Error
        perror("Error forking!");
        return EXIT_FAILURE;

    } else if (pid == 0) {

        // Child
        close(fd[1]);
        while ((nbytes = read(fd[0], &_char, 1)) != EOF) {
            if (nbytes == 0) …
Run Code Online (Sandbox Code Playgroud)

c pipe file-descriptor eof

0
推荐指数
1
解决办法
1598
查看次数

标签 统计

c ×1

eof ×1

file-descriptor ×1

pipe ×1