我想将字符串“一”发送到管道,然后等待一秒钟,然后将字符串“二”发送到管道。之后它应该打印到控制台。 如果我现在运行该程序,它会等待一秒钟,然后打印两个字符串而不是打印“一个”等待一秒钟并打印另一个字符串。
我怎样才能实现我的目标=
代码:
#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/