C++ 我想将两个字符串写入管道,两者之间有一个小的延迟

标签 c++ pipe fork

我想将字符串“一”发送到管道,然后等待一秒钟,然后将字符串“二”发送到管道。之后它应该打印到控制台。 如果我现在运行该程序,它会等待一秒钟,然后打印两个字符串而不是打印“一个”等待一秒钟并打印另一个字符串。

我怎样才能实现我的目标=

代码:

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

/* Read characters from the pipe and echo them to stdout. */

void
read_from_pipe (int file)
{
    FILE *stream;
    int c;
    stream = fdopen (file, "r");
    while ((c = fgetc (stream)) != EOF)
        putchar (c);
    fclose (stream);
}

/* Write some random text to the pipe. */

void
write_to_pipe (int file)
{
    FILE *stream;
    stream = fdopen (file, "w");
    fprintf (stream, "one\n");
    sleep(1);
    fprintf (stream, "two\n");
    fclose (stream);
}

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]);
        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]);
        return EXIT_SUCCESS;
    }
}

最佳答案

此行为是由缓冲引起的。更多信息:https://stackoverflow.com/a/23299046/4396133

使用fflush()将数据立即写入流,如下代码所示:

void
write_to_pipe (int file)
{
    FILE *stream;
    stream = fdopen (file, "w");
    fprintf (stream, "one\n");
    fflush(stream);
    sleep(1);
    fprintf (stream, "two\n");
    fflush(stream);
    fclose (stream);
}

关于C++ 我想将两个字符串写入管道,两者之间有一个小的延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58216057/

相关文章:

c++ - vector 订阅超出范围

c++ - 为什么 Qt .pro 文件会为平台提供错误,即使未选择或提及它也是如此?

windows - 如何将括号发送到由括号包围的管道中?

C叉区分父子

c - 在 fork 中写入和读取 - C

c++ - 计算结构大小而不填充字节的函数

C - Unix 管道,close() 影响输出?

c - Linux在父进程和子进程之间使用管道在c中传递值?

c - 多个子进程

c++ - 在不编辑标题的情况下取消命名空间类的全局化