如何在主进程和线程之间使用Unix管道? [英] How can Unix pipes be used between main process and thread?

查看:174
本文介绍了如何在主进程和线程之间使用Unix管道?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当信号从线程到达主进程时,我试图通过管道传送数据。



这是否可能?

如何做到这一点?






问题:




  1. 子线程读取数据,进入队列。

  2. 主应用程序有自己的东西,但是,当数据在队列中可用时,它应该由线程通知,并开始处理数据(主线程可以访问队列)

    解决方案

    / div>

    可以通过管道。



    第一步调用 pipe 获取管道:

      #include< unistd.h> 


    int main(...)
    {

    int fileDescriptors [2];
    pipe(fileDescriptors);

    步骤2将fileDescriptors [0]传递给主进程,将fileDescriptors [1]传递给线程。在Main中,您通过读取fileDescriptors [0]等待管道写入。

      ... 
    char msg [100];
    read(fileDescriptors [0],msg,100); // block until pipe read by
    }

    步骤3,从你的线程写入fileDescritpors [1]当信号发生时

      void signal_handler(int sig)
    {
    // Write to文件描述符
    if(sig == SIGKILL)
    {
    const char * msg =Hello Mama!
    write(fileDescriptors [1],msg,strlen(msg));
    }
    }


    I am trying to channel data via pipes whenever a signal arrives from a thread to the main process.

    Is this possible?
    How can this be done?


    The problem:

    1. A child thread reads data and puts it into a queue.
    2. Main application does its own stuff, however, when data is available on the queue, it should be notified by the thread, and start processing the data (main thread has access to the queue).

    How should this scenario be implemented?

    解决方案

    Yes its possible through pipes.

    Step one call pipe to get a pipe:

      #include <unistd.h>
    
    
      int main(...)
      {
    
        int fileDescriptors[2];
        pipe(fileDescriptors);
    

    Step 2 pass the fileDescriptors[0] to the main process, and fileDescriptors[1] to the thread. In Main you wait for the pipe to be written to to by reading from fileDescriptors[0]

        ...
        char msg[100];
        read(fileDescriptors[0], msg, 100);  // block until pipe is read
      }
    

    Step 3, from your thread write to fileDescritpors[1] when the signal occurs

     void signal_handler( int sig )
     {
         // Write to the file descriptor
         if (sig == SIGKILL)
         {
             const char* msg = "Hello Mama!";
             write(fileDescriptors[1], msg, strlen(msg));
         }
     }
    

    这篇关于如何在主进程和线程之间使用Unix管道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆