1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| #include <iostream> #include <sys/shm.h> #include <sys/ipc.h> #include <fcntl.h> #include <semaphore.h> #include <unistd.h> #include <string.h> using namespace std;
class Cnt{ public: int c; string s; Cnt():c(0),s(""){}; ~Cnt(){}; }; template <typename T> void check(const char* er, const T& a, const T& b) { if (a == b) { perror(er); exit(EXIT_FAILURE); } }
void run(Cnt &cnt,sem_t *nsem,void *addr,int size){ for(int i=0;i<3;i++){ sem_wait(nsem); memcpy(&(cnt.c),addr,size); cnt.c++; cout<<cnt.c<<"\n"; memcpy(addr,&(cnt.c),size); sem_post(nsem); } }
int main() { Cnt cnt; int size= sizeof(cnt.c); sem_t* nsem=sem_open("name_sem",O_CREAT,0666,1); check(string("sem_open").c_str(),nsem,SEM_FAILED); int fd=open("./shm",O_CREAT|O_RDWR,0666); check(string("open").c_str(),fd,-1); check(string("close").c_str(),close(fd),-1); key_t k=ftok("./shm",'A'); check(string("ftok").c_str(),k,-1); int sid=shmget(k,size,IPC_CREAT|0666); check(string("shmget").c_str(),sid,-1); void *addr = shmat(sid,nullptr,0); check(string("shmat").c_str(),addr,(void*)-1); pid_t cid=fork(); if(cid==-1){ perror("fork"); exit(EXIT_FAILURE); }else if(cid>0){ run(cnt,nsem,addr,size); }else{ run(cnt,nsem,addr,size); } if(cid>0){ check(string("shmdt").c_str(),shmdt(addr),-1); check(string("shmctl").c_str(),shmctl(sid,IPC_RMID,nullptr),-1); check(string("sem_close").c_str(),sem_close(nsem),-1); check(string("sem_unlink").c_str(),sem_unlink("name_sem"),-1); } return 0; }
|