개발자
signal.shared memory 두 ipc기법을 조합해서 공유메모리에 read/write 할 때 시그널을 주고 받도록 작성하는 c언어 코드를 알려주실 수 있나요?
답변 0
첫 답변을 기다리고 있어요.
지금 가입하면 모든 질문의 답변을 볼 수 있어요!
현직자들의 명쾌한 답변을 얻을 수 있어요.
이미 회원이신가요?
커리어리 AI 봇
GPT가 달아주는 답변입니다.
2024년 05월 28일
프로세스간에 데이터를 주고받는 IPC(Inter-Process Communication)기법 중 하나인 공유 메모리 기법을 사용하여, 프로세스가 공유 메모리에 read/write 작업을 할 때 signal을 보내도록 하는 C 코드는 다음과 같습니다. ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #define SHMSZ 27 void sigHandler(int); int main() { char c; int shmid; key_t key; char *shm,*s; //We'll name our shared memory segment "5678". key = 5678; //Create the segment. if ((shmid = shmget(key, SHMSZ, IPC_CREAT|0666)) < 0) { perror("shmget"); exit(1); } //Now we attach the segment to our data space. if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) { perror("shmat"); exit(1); } /* * Now put some things into the memory for the * other process to read. */ s = shm; for (c = 'a'; c <= 'z'; c++) *s++ = c; *s = NULL; /* * Trigger signal here after writing to shared memory */ kill(getpid(), SIGUSR1); // send self signal } void sigHandler(int sigNum) { printf("\n Signal received from shared memory write \n"); } ``` 이 코드에서는 공유 메모리를 생성하고 'a'부터 'z'까지의 문자를 공유 메모리에 write한 후, `kill(getpid(), SIGUSR1)` 함수를 통해 자체적으로 시그널을 보냅니다. 이 때 시그널 핸들러인 `sigHandler(int sigNum)` 함수가 호출되어 "Signal received from shared memory write"라는 메시지를 출력합니다. 이러한 방식으로, 공유 메모리에 read/write 작업이 일어날 때마다 각각의 프로세스에 시그널을 보내는 것이 가능합니다. 서로 다른 프로세스간에 시그널을 주고받기 위해서는 `getpid()` 대신 다른 프로세스의 PID를 사용하면 됩니다.
지금 가입하면 모든 질문의 답변을 볼 수 있어요!