[ACCEPTED]-How can Unix pipes be used between main process and thread?-unix
Yes its possible through pipes.
Step one 6 call pipe to get a pipe:
#include <unistd.h>
int main(...)
{
int fileDescriptors[2];
pipe(fileDescriptors);
Step 2 pass the fileDescriptors[0] to 5 the main process, and fileDescriptors1 to 4 the thread. In Main you wait for the pipe 3 to be written to to by reading from fileDescriptors[0]
...
char msg[100];
read(fileDescriptors[0], msg, 100); // block until pipe is read
}
Step 2 3, from your thread write to fileDescritpors1 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));
}
}
It can be done, but it's rather unnecessary. Pipes 4 are intended for inter-process communication. Threads 3 share the same memory and can therefore 2 communicate directly, as long as you use 1 locking correctly.
If you're talking about pipe()
rather than |
, then 4 yes. Pipes can generally just be treated 3 as a file descriptor. You just need to 2 open the pipe and cleanup the input in one 1 thread, and the output in the other.
As others have said, this may be more trouble 8 than it is worth.
However, if you insist.
Probably 7 easiest just to open two pipes using popen
and 6 rw
mode before spawning the thread. Choose 5 one for main-->thread and the other for 4 main<--thread and just go ahead.
Or you 3 could open a total of four file descriptors 2 after spawning, as if they were two different 1 processes
You could do that, apache has a similar 14 "graceful restart" option. (see 13 here). You would use something like:
#include <sys/types.h>
#include <signal.h>
kill(getppid(), SIGUSR1);
To send 12 a signal to the parent. Others have the 11 code above to spawn the file descriptors 10 and catch it on the parent side.
However, I 9 tend to avoid signals for scripted interprocess 8 communication, instead using them only for 7 "user sent" messages, like start/stop/restart/refresh. What 6 you replace them with depends on your usecase: you 5 could use a messaging variable, or if your 4 main process is in a server loop, you could 3 "select" on a pipe at the top of the loop to see 2 if the child has sent a refresh message. There 1 is probably a lot of others I'm missing.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.