[9] 프로세스 간 통신 - [System V IPC 대상] 공유 메모리(share memory)

[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; }

좋은 웹페이지 즐겨찾기