multithreading - How to send message (in C) from one thread to another? -
i'm trying send message 1 thread another. each thread knows thread id of other. how can send message between them?
i've seen proposed solutions (message queue, anonymous pipe, etc.) didn't them work. didn't understand previous descriptions enough, hence topic.
so sum up, shortest possible way send, let's message "hello!" thread thread, make 2nd thread show on stderr, , send 1st thread message 'hello back!'.
it's easy , didn't job of researching, i've been stuck time now, , can't find decent way this.
an example, it's pretty simple — first make pipe pipe()
. it creates 2 file descriptor — 1 reading, , second writing. here calling 2 times have both read , write sides. calling fork (that makes second thread), , write/read messages through pipes created.
#include <poll.h> #include <stdio.h> #include <string.h> #include <unistd.h> int wait_n_read(int fd, char* buf, int szbuf) { struct pollfd pfd = { .fd = fd, .events = pollin, .revents = 0 }; poll(&pfd, 1, -1); //wait event int ret = read(fd, buf, szbuf); if (ret == -1) { perror("in read()"); } return ret; } main(){ int chan[4]; enum{ thread1_read = 0, //read end parent thread2_write = 1, //write end child thread2_read = 2, //read end child thread1_write = 3 //write end parent }; if (pipe(&chan[thread1_read]) == -1 || (pipe(&chan[thread2_read]) == -1)){ perror("in pipe"); return 1; } switch(fork()) { case -1: perror("in fork()"); return 1; case 0:{ //it's child char buf[256]; memset(buf, 0, sizeof(buf)); if (wait_n_read(chan[thread2_read], buf, sizeof(buf)-1) == -1) return 1; fputs(buf, stderr); const char helloback[] = "hello back\n"; write(chan[thread2_write], helloback, sizeof(helloback)); return 0; } default: { //a parent const char hello[] = "hello\n"; write(chan[thread1_write], hello, sizeof(hello)); char buf[256]; memset(buf, 0, sizeof(buf)); if (wait_n_read(chan[thread1_read], buf, sizeof(buf-1)) == -1) return 1; fputs(buf, stderr); } } }
Comments
Post a Comment