代码参考网上其他人的,分三个文件
sm_common.h
#ifndef __SM_COMMON_H__
#define __SM_COMMON_H__
#include <pthread.h>
#define SM_BUF_SIZE 1024
#define SM_ID 0x1122
struct sm_msg
{
int flag;//标志位,0代表在写,1表示在读
pthread_mutex_t sm_mutex;//互斥锁
char buf[SM_BUF_SIZE];//存放的数据
};
#endif
sm_server.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <pthread.h>
#include "sm_common.h"
int main(void)
{
int shm_id = -1;
int ret = -1;
int key = -1;
int running = 1;
struct sm_msg *msg = NULL;
void *shared_memory = NULL;
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);//init mutex lock
pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);//set mutex lock ,other procecc can use
shm_id = shmget((key_t)SM_ID, sizeof(struct sm_msg), 0666|IPC_CREAT);
if(shm_id <