#include #include #include #include #include #include #define TESTSEMID 100 #define SEMSIZE 1 #if defined(__GNU_LIBRARY__) && !defined(_SEM_SEMUN_UNDEFINED) /* union semun is defined by including */ #else /* according to X/OPEN we have to define it ourselves */ union semun { int16_t val; /* value for SETVAL */ struct semid_ds *buf; /* buffer for IPC_STAT, IPC_SET */ unsigned short int *array; /* array for GETALL, SETALL */ struct seminfo *__buf; /* buffer for IPC_INFO */ }; #endif int test_semid; void to_show(){ union semun arg; unsigned short int allval[SEMSIZE]; int i; arg.array = allval; if (semctl(test_semid, 0 , GETALL, arg) < 0) { printf("semctl failed for[%s].\n", strerror(errno)); return ; } for( i=0; i < SEMSIZE; i++) printf("\t semval[%d] = %d \n", i , allval[i]); return; } int create_test_semaphore(void) { int key, i; char fn[100]; union semun arg; unsigned short int allval[SEMSIZE]; sprintf(fn, "."); if ((key = ftok(fn, TESTSEMID)) < 0) { printf("ftok failed for[%s].\n", strerror(errno)); return -1; } if ((test_semid = semget(key, SEMSIZE, IPC_CREAT | IPC_EXCL | 0666)) < 0) { if (errno == EEXIST) { printf("Test semaphore has existed.\n"); printf("Get test semaphore...\n"); if ((test_semid = semget(key, 0, 0666)) < 0) { printf("semget failed for[%s].\n", strerror(errno)); return -1; } else { to_show(); printf("Get test semaphore successfully.\n"); return 0; } } printf("semget failed[%s].\n", strerror(errno)); return -1; } for (i = 0; i< SEMSIZE; i++) allval[i] = 8; arg.array = allval; if (semctl(test_semid, SEMSIZE, SETALL, arg) < 0) { printf("semctl failed for[%s].\n", strerror(errno)); return -1; } return 0; } int mutex_op_semaphore(int op) { int i; struct sembuf oparray[SEMSIZE]; for (i = 0; i < SEMSIZE; i++) { oparray[i].sem_num = i; oparray[i].sem_op = op; oparray[i].sem_flg = SEM_UNDO; } if (semop(test_semid, oparray, SEMSIZE) < 0) { printf("semop failed for[%s].\n", strerror(errno)); return -1; } else return 0; } int main(void) { int ret; // printf("Create test semaphore...\n"); if (create_test_semaphore() < 0) { printf("Create test semaphore failed.\n"); return -1; } //else //printf("Create test semaphore successfully.\n"); printf("before Get semaphore exclusively...\n"); to_show(); if (mutex_op_semaphore(-1) < 0) { printf("Get test semaphore failed.\n"); return -1; } else printf("after Get semaphore ...\n"); to_show(); sleep(5); printf("before release semaphore exclusively...\n"); to_show(); if (mutex_op_semaphore(1) < 0) { printf("Release test semaphore failed.\n"); return -1; } else printf("before release semaphore exclusively...\n"); to_show(); return 0; }