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

你可能感兴趣的:(多进程,共享内存,型号处理)