繁体   English   中英

C++ 我想将两个字符串写入 pipe 之间的延迟很小

[英]C++ I Want to write two strings into pipe with a small delay between

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

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

代码:

#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()立即向 stream 写入数据,如下代码所示:

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);
}

暂无
暂无

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

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