共享内存、信号量 进程间通讯应用示例

使用POSIX机制共享内存、信号量的API,实现进程通讯。

相对于System V IPC机制,POSIX更简单易用

服务端:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include         
#include   
#include 
#include 
using namespace std;
char   *ptr;
#define BUFF_SIZE (1024)
int exit_flag = 0;
void signalHandler(int num)
{
	
	exit_flag = 1;
	printf ( "exit!\n" );
}

int main() {
	char * sem_name = "/my_semaphore";//必须加斜杠‘/’,不得用相对路径
    sem_t *semaphore = sem_open(sem_name, O_CREAT, 0644, 0);
	if (semaphore == SEM_FAILED) {
		perror("sem_open failed\n");
		return -1;
    }
	
	int   fd;
	fd = shm_open( "/shm_region" , O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);//必须加斜杠‘/’,不得用相对路径
	if   (fd<0) {
		printf ( "shm_open failed\n" );
		return   0;
	}
	ftruncate(fd, BUFF_SIZE);
	ptr = (char*)mmap(NULL, BUFF_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	if   (ptr == MAP_FAILED) {
		printf ( "error map\n" );
		return   0;
	}
	signal(SIGINT, signalHandler);
	int cnt=0;
	while(!exit_flag)
	{
		sprintf((char*)ptr,"%s,%d","test data",cnt++);
		sem_post(semaphore);//发送信号
		printf("send: %s\n",ptr);
		if(cnt==10)
		{
			break;
		}
		sleep(5);
	}
	munmap(ptr,BUFF_SIZE);
	close(fd);
	sem_close(semaphore);
	sem_unlink(sem_name);	
	return 0;
	
}

客户端:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include         
#include   
#include 
#include 
char   *ptr;
#define BUFF_SIZE (1024)
int exit_flag = 0;
void signalHandler(int num)
{
	
	exit_flag = 1;
	printf ( "exit!\n" );
}
int main() {
	
	char * sem_name = "/my_semaphore";//必须加斜杠‘/’,不得用相对路径
    sem_t *semaphore = sem_open(sem_name, O_EXCL, 0644, 0);
	if (semaphore == SEM_FAILED) {
		perror("sem_open failed");
		return -1;
    }
	
	int   fd;
	fd = shm_open( "/shm_region" , O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);//必须加斜杠‘/’,不得用相对路径
	if   (fd<0) {
		printf ( "error open region\n" );
		return   0;
	}
	ftruncate(fd, BUFF_SIZE);
	ptr = (char*)mmap(NULL, BUFF_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	if   (ptr == MAP_FAILED) {
		printf ( "error map\n" );
		return   0;
	}
	signal(SIGINT,signalHandler);
	while(!exit_flag)
	{
		sem_wait(semaphore);//等待信号
		std::cout << "recv: " << ptr << std::endl;
		if(0==memcmp(ptr,"test data,9",strlen("test data,9")))
		{
			break;
		}		
	}
	munmap(ptr,BUFF_SIZE);
	close(fd);
	sem_close(semaphore);
	sem_unlink(sem_name);
	return 0;
}

注:编译时必须加 -lpthread  -lrt

你可能感兴趣的:(c++)