한 스레드에서 다른 스레드로 메시지를 보내려고합니다. 각 스레드는 다른 스레드의 ID를 알고 있습니다. 그들 사이에 어떻게 메시지를 보낼 수 있습니까?
이미 몇 가지 제안 된 솔루션 (메시지 대기열, 익명 파이프 등)을 보았지만 솔직히 작동하지 않았습니다. 분명히 나는 이전 설명을 충분히 이해하지 못했기 때문에이 주제를 다루었습니다.
요약하자면 가능한 가장 짧은 전송 방법입니다. "Hello!"라는 메시지를 봅시다. 스레드에서 다른 스레드로, 두 번째 스레드가 stderr에 표시하도록 만들고 첫 번째 스레드 메시지 'Hello back!'으로 다시 보냅니다.
아마 매우 쉬웠고 연구를 잘하지 못했지만 지금은 한동안 갇혀 있었기 때문에 적절한 방법을 찾을 수 없습니다.
예를 들어, 매우 간단합니다. 먼저 pipe()
. 두 개의 파일 설명자를 만듭니다. 하나는 읽기 용이고 다른 하나는 쓰기 용입니다. 여기서 우리는 읽기와 쓰기를 모두 두 번 호출합니다. 그런 다음 fork (두 번째 스레드를 만드는)를 호출 하고 생성 한 파이프를 통해 메시지를 쓰고 읽습니다.
#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 for an 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 for parent
thread2_write = 1, //write end for child
thread2_read = 2, //read end for child
thread1_write = 3 //write end for 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 a 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);
}
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다