How can Unix pipes be used between main process and thread?

前端 未结 5 660
慢半拍i
慢半拍i 2021-01-05 08:31

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 pr

5条回答
  •  遥遥无期
    2021-01-05 08:36

    Yes its possible through pipes.

    Step one call pipe to get a pipe:

      #include 
    
    
      int main(...)
      {
    
        int fileDescriptors[2];
        pipe(fileDescriptors);
    

    Step 2 pass the fileDescriptors[0] to the main process, and fileDescriptors1 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 fileDescritpors1 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));
         }
     }
    

提交回复
热议问题