简体   繁体   English

为什么子进程“读取”功能不返回(我认为它将返回-1),并且子进程“ printf”功能不起作用

[英]Why the son process “read” function don't return (I think it will return -1), and the son process 'printf' function does not work

Why the son process "read" function don't return (I think it will return -1), and the son process 'printf' function does not work. 为什么子进程“读取”功能不返回(我认为它将返回-1),并且子进程“ printf”功能不起作用。

#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main() {
    int fd[2];
    pipe(fd);
    pid_t pid = fork();
    if(pid == 0) {
        char buf[128] = {0};
        int ret = read(fd[0], buf, sizeof buf);
        printf("Son ret is %d\n", ret);
        write(STDOUT_FILENO, buf, ret);
    }
    else if(pid > 0){
        char buf[128] = "hello\n\0";
        write(fd[1], buf, sizeof buf);
        memset(buf, 0, sizeof buf);
        int ret = read(fd[0], buf, sizeof buf);
        printf("Dad ret is %d\n", ret);
        write(STDOUT_FILENO, buf, ret);
    }
    return 0;
}
  1. It is not defined which process will get the buffer. 没有定义哪个进程将获取缓冲区。 Maybe the parent, maybe the child, maybe both will get a half of it each. 也许父母,也许是孩子,也许两者都会各得一半。 Maybe in your experiment the father gets all of the buffer, but nobody guarantees that it will always happen. 也许在您的实验中,父亲获得了所有缓冲,但没有人保证它会一直发生。
  2. A process should close an unused write end of its pipe, otherwise it will never see an EOF on the read end. 进程应关闭其管道的未使用写端,否则它将永远不会在读端看到EOF。 So the child should call close(fd[1]) before doing anything else. 因此,孩子应该在执行其他任何操作之前先调用close(fd[1])
  3. (Unrelated) An explicit \\0 at the end of a string literal is unnecessary. (无关)在字符串文字的末尾不需要显式\\0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM