//http://blog.csdn.net/KataDoc360/archive/2008/11/21/3348023.aspx
//进程间共享内存和信号灯同时使用
//share.h
#define sem_key 2010 #define shm_key 2011 #define SEM_PERM 0600 #define SHM_PERM 0600
struct content { int nput; int nval; };
//client.cpp
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/shm.h>
#include "share.h"
void lock_sem() { struct sembuf ops[2]; ops[0].sem_num = 0; ops[0].sem_op = 0; ops[0].sem_flg = 0; ops[1].sem_num = 0; ops[1].sem_op = 1; ops[1].sem_flg = SEM_UNDO;
int nsemid = semget(sem_key, 1, SEM_PERM|IPC_CREAT); if (nsemid < 0) { perror("semget"); } int nret = semop(nsemid, &ops[0], 2); if (nret < 0) { perror("semop"); } }
void unlock_sem() { struct sembuf ops[1]; ops[0].sem_num = 0; ops[0].sem_op = -1; ops[0].sem_flg = SEM_UNDO|IPC_NOWAIT;
int nsemid = semget(sem_key, 1, SEM_PERM|IPC_CREAT); if (nsemid < 0) { perror("semget"); } int nret = semop(nsemid, &ops[0], 1); if (nret < 0) { perror("semop"); } }
int main() { int nshmid = shmget(shm_key, sizeof(content), SHM_PERM|IPC_CREAT); if (nshmid < 0) { perror("shmget"); }
struct content* p = (content*)shmat(nshmid, NULL, 0); lock_sem(); p->nput++; p->nval++; unlock_sem();
return 0; }
//server.cpp
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/shm.h>
#include "share.h"
void lock_sem() { struct sembuf ops[2]; ops[0].sem_num = 0; ops[0].sem_op = 0; ops[0].sem_flg = 0; ops[1].sem_num = 0; ops[1].sem_op = 1; ops[1].sem_flg = SEM_UNDO;
int nsemid = semget(sem_key, 1, SEM_PERM|IPC_CREAT); if (nsemid < 0) { perror("semget"); } int nret = semop(nsemid, &ops[0], 2); if (nret < 0) { perror("semop"); } }
void unlock_sem() { struct sembuf ops[1]; ops[0].sem_num = 0; ops[0].sem_op = -1; ops[0].sem_flg = SEM_UNDO|IPC_NOWAIT;
int nsemid = semget(sem_key, 1, SEM_PERM|IPC_CREAT); if (nsemid < 0) { perror("semget"); } int nret = semop(nsemid, &ops[0], 1); if (nret < 0) { perror("semop"); } }
void delete_sem() { int nsemid = semget(sem_key, 1, SEM_PERM|IPC_CREAT); if (nsemid < 0) { perror("semget"); }
semctl(nsemid, 0, IPC_RMID); }
int main() { int nshmid = shmget(shm_key, sizeof(content), SHM_PERM|IPC_CREAT); if (nshmid < 0) { perror("shmget"); }
struct content *p = (content*)shmat(nshmid, NULL, 0); lock_sem(); printf("nput:%d = %d\n", p->nput, p->nval); unlock_sem();
shmctl(nshmid, IPC_RMID, 0); delete_sem();
return 0; }
|