C 管道写/读优先级

标签 c pipe fork

我试图理解管道和 C 语言中 fork 的使用。下面是一个调用 fork() 的代码示例,然后:

  • 子进程:读取管道并将内容打印到控制台。
  • 父进程:在 pipe 中写入“hello world”。

    int main(void)
    {
    pid_t pid;
    int mypipe[2];
    
    /* Create the pipe. */
    if (pipe(mypipe))
    {
        fprintf(stderr, "Pipe failed.\n");
        return EXIT_FAILURE;
    }
    /* Create the child process. */
    pid = fork();
    if (pid == (pid_t)0)
    {
        /* This is the child process.
        Close other end first. */
        close(mypipe[1]);
        read_from_pipe(mypipe[0]);//read pipe and print the result to console
        return EXIT_SUCCESS;
    }
    else if (pid < (pid_t)0)
    {
        /* The fork failed. */
        fprintf(stderr, "Fork failed.\n");
        return EXIT_FAILURE;
    }
    else
    {
        /* This is the parent process.
        Close other end first. */
        close(mypipe[0]);
        write_to_pipe(mypipe[1]);//write "hello world" to the pipe
        return EXIT_SUCCESS;
    }
    }
    

我的理解是,我们使用管道,把管道当做文件来处理,这样子进程和父进程就可以进行通信了。 (这是正确的吗?)现在,由于父项和子项都在使用管道,子项是否会读取一个空的 pipe ?或者 pipe 会是“Hello world”吗?为什么?我的猜测是它是随机的,因为子进程和父进程同时运行。这是真的 ?

最佳答案

根据 man 7 pipe,“如果进程试图从空管道读取数据,则 read(2) 将阻塞直到数据可用。”。

因此,如果read发生在write之前,它将等到write完成。

反过来,如果 read 发生在 write 之后,很明显它会返回消息。

并且这些情况中至少有一个必须是真实的,因为,仍然根据 man 7 pipe,“POSIX.1-2001 表示小于 PIPE_BUF 字节的 write(2)s 必须是atomic”,PIPE_BUF 通常足够大,可以容纳比“Hello World”更多的内容。

所以 read 将返回“Hello world”。

关于C 管道写/读优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29873037/

相关文章:

http - 如何将文件提供给telnet

node.js - Node : How can I use pipe and change one file from a multipart

linux - 如何使用 xargs 将 ls 通过管道传输到 cat 中,以便列出文件名?

python - 如何等待父进程退出子进程?

c - 应用程序可执行文件和 3d 方库之间的嗅探函数调用

c - Makefile 未执行,错误需要符号

c - 如何从CHILD PROCESS中获取返回值?

c - c中的Execl(传递参数)

在C中将两个函数连接成一个

c - 如何在不使用 strcpy 函数的情况下初始化结构中的字符串?