Code:# include < unistd.h> # include < stdlib.h> # include < stdio.h> # include < sys/types.h> # include < sys/ipc.h> # include < sys/sem.h> #ifndef _SEMUN_H #define _SEMUN_H union semun{ int val; struct semid_ds * MyBuff; unsigned short int * MyArr; struct seminfo *__MyBuff; }; # endif static int set_semvalue(void); static void DeleteSem(void); static int semaphore_p(void); static int Sem(void); static int sem_id; int main(int argc, char *argv[]) { int i, Puase; char Output = 'O'; srand((unsigned int) getpid()); sem_id = semget((key_t)1234,1,0666| IPC_CREAT); if ( argc > 1 ) { if (!set_semvalue()) { fprintf(stderr, "Failed to initialize semapore "); exit(EXIT_FAILURE); } Output = 'X'; sleep(2); } for ( i=0; i<10;i++) { if (!semaphore_p()) exit(EXIT_FAILURE); printf("%c", Output); fflush(stdout); Puase = rand() % 3; sleep(Puase); printf("%c", Output);fflush(stdout); if (!semaphore_p()) exit(EXIT_FAILURE); Puase = rand() % 2; sleep(Puase); } printf(" %d ", getpid()); if (argc >1 ) { sleep(10); DeleteSem(); } exit(EXIT_SUCCESS); } static int set_semvalue(void) { union semun MySemUnion; MySemUnion.val = 1; if (semctl(sem_id,0,SETVAL, MySemUnion) == -1) return(0); return(1); } static void DeleteSem(void) { union semun MySemUnion; if (semctl(sem_id,0, IPC_RMID, MySemUnion) == -1) fprintf(stderr, "Failed "); } static int semaphore_p(void) { struct semMyBuff sem_b; sem_b.sem_num = 0; sem_b.sem_op = -1; sem_b.sem_flg = SEM_UNDO; if (semop(sem_id, &sem_b,1) == -1) { fprintf(stderr, "semaphore_p failed "); return(0); } return(1); }
Bookmarks