System V共享内存使用实例

#include <stdlib.h>
#include <stdio.h>
#include <sys/shm.h>
#include <sys/errno.h>
#include <pthread.h>
#include <string.h>
#include <malloc.h>
#include <signal.h>

#define BUFFER_SIZE 1000

typedef struct SHMSTRU
{
	pthread_mutex_t lock;
	char buffer[BUFFER_SIZE];
}ShmStru;

typedef enum
{
	false,
	true
}bool;

void signalCancel(int);

bool isExit = false;

int main(void)
{
	int key = 1000;
	int shmid = 0;	
	ShmStru *pShmStru = NULL;
	int exist = 0;
	int cPid = 0;
	int ret = 0;

	struct shmid_ds shmDs;

	signal(SIGINT, signalCancel);

	shmid = shmget(key, sizeof(ShmStru), IPC_EXCL | IPC_CREAT);
	if (-1 == shmid)
	{
		if (EEXIST == errno)
		{
			printf("INFO: The shared memory is exist!\n");
			shmid = shmget(key, 0, 0);
			exist = 1;
		}
		else
		{
			printf("ERROR: Create shared memory failed, ErrorCode: %d!\n", errno);
			return -1;
		}
	}

	memset(&shmDs,0x00, sizeof(struct shmid_ds));
	
	//Get the info of the shared memory
	if (exist)
	{
		ret = shmctl(shmid, IPC_STAT, &shmDs);
		if (-1 != ret)
		{
			printf("INFO: The current attache processes num: %d!\n", (int)shmDs.shm_nattch);
		}
	}	

	pShmStru = (ShmStru *)shmat(shmid, 0, 0);
	if ((void *)-1 == pShmStru)
	{
		perror("");
		return -1;
	}	

	if (!exist)
	{
		strcpy(pShmStru->buffer, "The initial information!");
		pthread_mutex_init(&pShmStru->lock, 0);
	}

	cPid = fork();
	if (0 == cPid)
	{
		while (!isExit)
		{
			pthread_mutex_lock(&pShmStru->lock);
			printf("Child: The info in shared memory is %s!\n", pShmStru->buffer);
			strcpy(pShmStru->buffer, "The information set by the child!");	
			pthread_mutex_unlock(&pShmStru->lock);
			usleep(1000000);
		}
		shmdt(pShmStru);
	}
	else
	{
		while (!isExit)
		{
			pthread_mutex_lock(&pShmStru->lock);
			printf("Parent: The info in shared memory is %s!\n", pShmStru->buffer);
			strcpy(pShmStru->buffer, "The information set by the parent!");
			pthread_mutex_unlock(&pShmStru->lock);
			usleep(1000000);
		}
		shmdt(pShmStru);
		shmctl(shmid, IPC_RMID, 0);
	}
	
	return 1;
}

void signalCancel(int i)
{
	printf("INFO: Catch the cancel signal!\n");
	isExit = true;
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值