How can Unix pipes be used between main process and thread?
Solution 1
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 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));
}
}
Solution 2
It can be done, but it's rather unnecessary. Pipes are intended for inter-process communication. Threads share the same memory and can therefore communicate directly, as long as you use locking correctly.
Solution 3
If you're talking about pipe()
rather than |
, then yes. Pipes can generally just be treated as a file descriptor. You just need to open the pipe and cleanup the input in one thread, and the output in the other.
Admin
Updated on June 14, 2022Comments
-
Admin almost 2 years
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:
- A child thread reads data and puts it into a queue.
- 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?
-
Doug T. almost 15 yearsI would say pipes or a condition variable would be preferred over shared memory because you have to worry about all the problems with locks, shared memory, etc.
-
Greg Rogers almost 15 yearsThe main benefit to using pipes is that a single thread can wait and read from multiple pipes, instead of just a single queue signalled with a semaphore.
-
Admin almost 15 yearsBTW, I only have one thread. I wonder if shared memory would be a better/easier solution.
-
Doug T. almost 15 yearsSasha are you comfortable with mutexes and locking? Have you had to deal with deadlocks or race-conditions in the past? Are you familiar with how difficult these can be to debug? I would suggest sticking with pipes as a simpler solution.
-
novelistparty over 6 yearsread/write to pipes in glibc is atomic if the data is under a certain size gnu.org/software/libc/manual/html_node/…