C++ 我想将两个字符串写入管道,中间有一小段延迟
C++ I Want to write two strings into pipe with a small delay between
我想将字符串"一"发送到管道,然后等待一秒钟并将字符串"二"发送到管道。之后,它应该被打印到控制台。 如果我现在运行该程序,它会等待一秒钟,然后打印两个字符串而不是打印"一个"等待一秒钟并打印另一个字符串。
我怎样才能实现我的目标=
法典:
#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);
}
相关文章:
- 2D数组来自文本输入,中间有空格
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- IPC使用多个管道和分支进程来运行Python程序
- 如何创建函数管道,以便函数一个接一个地运行?
- Gstreamer 管道从命令 lne 到 c 代码
- 外壳包装器句柄/执行交互式命令管道C++ UNIX
- 将旧管道转换为现代 openGL 时出现问题
- 递归形成字符串中所有数字字符的中间和?
- 如何使用管道在父级和子级之间来回传递文件
- 在没有管理员权限的情况下连接到同一网络中的命名管道
- 链表错误的中间
- 如何测量管道延迟?
- 我如何使用此程序管道多个命令?C++
- 先进先出:一个进程永远不会从管道读取
- Node.js fs.open() 在尝试打开 4 个以上的命名管道 (FIFO) 后挂起
- 使用模板而不是虚拟方法的管道模式
- 我可以写入关闭的套接字并强制纠正损坏的管道错误吗?
- 在 Azure DevOps 构建管道中使用英特尔C++编译器为 Linux 环境构建C++代码
- Opencv GStreamer管道在Raspberry Pi 4上不起作用
- C++ 我想将两个字符串写入管道,中间有一小段延迟