#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <wait.h>
#include <fcntl.h>
#include <string.h>
#include <signal.h>
#include <pthread.h>
#include <time.h>
#include <stdarg.h>
#include<sys/mman.h>
#include<semaphore.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/select.h>
#include <sys/shm.h>
#include <sys/sem.h>
#define RCH1 0x52434831
#define RCH2 0x52434832
#define RCH3 0x52434833
#define RCH4 0x52434834
#define RCH5 0x52434835
typedef struct{
pthread_mutex_t mutex;
pthread_mutexattr_t mutexattr;
int flag ;
char buf[1];
}SHM;
创建共享内存并初始化锁:
#include"common.h"
SHM *shm = NULL;
int main()
{
int id;
int key=getpid();
id=shmget(key,100,0666|IPC_CREAT);//创建共享内存,注意读写权限
printf("id = %d\n",id);
char buf[]="abcdefghijkl";
shm=shmat(id,NULL,0);//获取共享内存起始地址
pthread_mutexattr_init(&shm->mutexattr);
pthread_mutexattr_setpshared(&shm->mutexattr,PTHREAD_PROCESS_SHARED);//第二个参数设置为进程锁,默认为线程锁
pthread_mutex_init(&shm->mutex,&shm->mutexattr);
memcpy(shm->buf,buf,sizeof(SHM));
shm->flag=0;
sleep(100);
shmdt(shm);//与共享内存断开连接
shmctl(id,IPC_RMID,NULL);//销毁共享内存
}
访问共享内存并打印flag:
#include"common.h"
SHM *shm = NULL;
int main(int argc,char*argv[])
{
int id=atoi(argv[1]);
shm=shmat(id,NULL,0);//获取共享内存起始地址
while(1){
pthread_mutex_lock(&shm->mutex);//上锁
printf("增加前:buf = %s,flag =%d\n",shm->buf,shm->flag++);
sleep(1);
shm->flag--;
printf("增加后:buf = %s,flag =%d\n",shm->buf,shm->flag);
pthread_mutex_unlock(&shm->mutex); //解锁
sleep(1);
}
}
注意编译的时候需要 -lpthread。
如果不加上锁,打印的结果flag就会出现 0,1,2 ....这些值,
加上锁之后,打印的flag只能为0;