简体   繁体   English

后台传输到标准输出

[英]Pipe to standard output in background

I have the following scheme: 我有以下方案:

\
 + granpa
    |
    +--- uncle
    |
    +--- dad
          |
          +--- son1
          +--- son2
          +--- son3

Uncle should be the only one controlling output, so I thought of using a pipe() created by granpa and shared with sons across fork() . 叔叔应该是唯一的控制输出,因此我想到了使用由granpa创建并在fork()中与儿子共享的pipe() () So far so good. 到现在为止还挺好。

The problem is that uncle also reads from a System V Message Queue ( msgget() ) in a infinite loop, hence acting as a server. 问题在于, 叔叔还无限循环地从System V消息队列( msgget() )读取数据,因此充当服务器。

My problem is: in a scenario where we don't have multi-threading, how can these operations be done at the same time? 我的问题是:在没有多线程的情况下,如何同时执行这些操作?

A couple of solutions that came to my mind include: 我想到的一些解决方案包括:

  1. dup -ing pipe to standard output using dup2() , but it didn't work for unknown reasons; 使用dup2()管道dup -ing到标准输出,但是由于未知原因,它不起作用; I guess it's because the kernel doesn't automatically copy data from pipe buffer to terminal output memory, that would be too cool. 我猜这是因为内核不会自动将数据从管道缓冲区复制到终端输出内存,这太酷了。
  2. Background copying data from pipe buffer with splice() or tee() , but it looks like they are all blocking and won't execute in background (or perhaps they do and I'm doing something wrong). 使用splice()tee()从管道缓冲区进行后台复制数据,但看起来它们都被阻塞了,不会在后台执行(或者它们确实在做,而我做错了)。
  3. Using select() to determine at every cycle if I have a message or something to print, but unfortunately System V Message Queues aren't file descriptors in the Linux kernel (and I have no plans to make a custom version of the kernel as someone on the internet did exactly for this issue, absolutely). 使用select()在每个周期确定我是否有消息或要打印的东西,但是不幸的是,System V消息队列不是Linux内核中的文件描述符(而且我没有计划以某个人的身份创建内核的自定义版本)完全是在互联网上做到的)。

Another bunch of solutions that could actually work but kinda break the logic are: 可能实际上可行但有点违反逻辑的另一种解决方案是:

  1. Using only a System V Message Queue with a very big struct and using the msgtype field to determine whether I'm asking for something or want to print something. 仅使用结构非常大的System V消息队列,并使用msgtype字段来确定我要的是内容还是要打印的内容。 Awful. 可怕。
  2. Insted of using a System V Message Queue, use a socketpair() and the do select() or poll() or whatever. 在使用System V消息队列的情况下,请使用socketpair()和do select()poll()或其他方法。 This is my final solution, but if someone knows how to do it with System V Message Queues its preferred. 这是我的最终解决方案,但是如果有人知道如何使用System V Message Queues,那么它是首选。

You could try looking into the Linux D-Bus . 您可以尝试研究Linux D-Bus It was met to simplify large multi piped projects like this and give the client program much less lines to work with. 这样可以简化大型的多管道项目,并减少客户程序的工作量。

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

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