[9] 프로세스 간 통신 - [System V IPC 대상] 공유 메모리(share memory)
/*Writer.c*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define N 64
typedef struct
{
pid_t pid;
char buf[N];
} SHM;
void handler(int signo)
{
//printf("get signal
");
return;
}
int main()
{
key_t key;
int shmid;
SHM *p;
pid_t pid;
if ((key = ftok(".", 'm')) < 0)
{
perror("fail to ftok");
exit(-1);
}
signal(SIGUSR1, handler);
if ((shmid = shmget(key, sizeof(SHM), 0666|IPC_CREAT|IPC_EXCL)) < 0)
{
if (EEXIST == errno)
{
shmid = shmget(key, sizeof(SHM), 0666);
p = (SHM *)shmat(shmid, NULL, 0);
pid = p->pid;
p->pid = getpid();
kill(pid, SIGUSR1);
}
else
{
perror("fail to shmget");
exit(-1);
}
}
else
{
p = (SHM *)shmat(shmid, NULL, 0);
p->pid = getpid();
pause();
pid = p->pid;
}
while ( 1 )
{
printf("write to shm : ");
fgets(p->buf, N, stdin);
kill(pid, SIGUSR1);
if (strcmp(p->buf, "quit
") == 0) break;
pause();
}
shmdt(p);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
/*Reader.c*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define N 64
typedef struct
{
pid_t pid;
char buf[N];
} SHM;
void handler(int signo)
{
//printf("get signal
");
return;
}
int main()
{
key_t key;
int shmid;
SHM *p;
pid_t pid;
if ((key = ftok(".", 'm')) < 0)
{
perror("fail to ftok");
exit(-1);
}
signal(SIGUSR1, handler);
if ((shmid = shmget(key, sizeof(SHM), 0666|IPC_CREAT|IPC_EXCL)) < 0)
{
if (EEXIST == errno)
{
shmid = shmget(key, sizeof(SHM), 0666);
p = (SHM *)shmat(shmid, NULL, 0);
pid = p->pid;
p->pid = getpid();
kill(pid, SIGUSR1);
}
else
{
perror("fail to shmget");
exit(-1);
}
}
else
{
p = (SHM *)shmat(shmid, NULL, 0);
p->pid = getpid();
pause();
pid = p->pid;
}
while ( 1 )
{
pause();
if (strcmp(p->buf, "quit
") == 0) exit(0);
printf("read from shm : %s", p->buf);
kill(pid, SIGUSR1);
}
return 0;
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
9-1. 구조체와 클래스 비교, 구조체 개념(struct)구조체와 클래스는 프로그램 코드의 구성요소가 되는 범용 구조이다. 상수, 변수, 그리고 함수를 정의하는 것과 같은 구문을 사용해서 구조체와 클래스에 프로퍼티와 메서드를 기능적으로 추가할 수 있다. 스위프트에서 클래스...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.