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

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

本文关键字:管道 中间 延迟 小段 字符串 两个 C++      更新时间:2023-10-16

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

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

法典:

#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, "onen");
sleep(1);
fprintf (stream, "twon");
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, "onen");
fflush(stream);
sleep(1);
fprintf (stream, "twon");
fflush(stream);
fclose (stream);
}