linux c語言進程間通信-共享內存

以下爲兩個進程,write進程向共享內存寫數據,reader進程向共享內存讀取數據,代碼如下:

1.write.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\n");
	return;
}

void keycontrol(int signo)
{
	printf("keycontrol is : %d\n",signo);
	if(signo == SIGINT)
	{
		return;
	}
}

int main()
{
	key_t key;
	int shmid;
	SHM *p;
	pid_t pid;

	//建立IPC通訊,獲取key值
	if((key = ftok(".",'m')) < 0)
	{
		perror("fail to ftok");
		exit(-1);
	}



	signal(SIGUSR1,handler);
	signal(SIGINT,keycontrol); 
	// 獲取共享內存
	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;
	}

	printf("shmid = %d\n",shmid);
	while(1)
	{
		printf("write to shm:");
		fgets(p->buf,N,stdin);
		kill(pid,SIGUSR1);
		if(strcmp(p->buf,"quit\n")==0)
			break;
		pause();
	}
	// 斷開連接
	shmdt(p);
	shmctl(shmid,IPC_RMID,NULL);

	return 0;
}

2.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\n");
	return;
}

int main()
{
	key_t key;
	int shmid;
	SHM *p;
	pid_t pid;

	// 獲取key值
	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\n") == 0)
			exit(0);
		printf("read from shm:%s",p->buf);
		kill(pid,SIGUSR1);
	}

	return 0;
}


發佈了69 篇原創文章 · 獲贊 46 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章