自测之Lesson12:信号量
题目:创建一个包含5个信号量的信号集。
完成代码:
#include <stdio.h> #include <sys/ipc.h> #include <sys/sem.h> #include <string.h> #define SEM_NUM 5 // 信号量的个数 // 创建一个信号集 int main() { key_t key; key = ftok("test", 1); // 创建key if (key == -1) { perror("fail ftok"); return -1; } int semid; semid = semget(key, 5, IPC_CREAT | 0664); // 创建一个包含5个信号量的信号集 if (semid == -1) { perror ("fail semget"); return -1; } printf("semid: %d\n", semid); return 0; }
题目:编写一个程序,要求:实现信号量的P、V、Z操作。
完成代码:
#include <stdio.h> #include <sys/ipc.h> #include <sys/sem.h> #include <string.h> #include <stdlib.h> #define SEM_NUM 5 void initSemaphore(int semid) { unsigned short semInit[SEM_NUM]; printf("init [%d] semaphore: ", SEM_NUM); int i; for (i = 0; i != SEM_NUM; i++) { int n; scanf("%d", &n); semInit[i] = n; } semctl(semid, SEM_NUM, SETALL, semInit); } void semop_PVZ(int semid, char flag) { struct sembuf sops[SEM_NUM]; int arr[SEM_NUM]; int isign = 1; switch(flag) { case 'p': isign = -1; break; case 'v': isign = 1; break; case 'z': isign = 0; break; case 'i': initSemaphore(semid); return; default: return; } setbuf(stdout, NULL); while(1) { printf("[%c]:", flag); scanf ("%d%d%d%d%d", arr, arr + 1, arr + 2, arr + 3, arr + 4); int i = 0; int cnt = 0; for (i = 0; i != SEM_NUM; i++) { if (arr[i] == 0) { continue; } sops[cnt].sem_num = i; sops[cnt].sem_op = arr[i] * isign; sops[cnt].sem_flg = 0; cnt++; } int iRet; iRet = semop(semid, sops, cnt); if (iRet == -1) { perror("fail semop"); return; } } } int main(int argc, char **argv) { if (argc != 2 || (strcmp(argv[1], "p") && strcmp(argv[1], "v") && strcmp(argv[1], "q") &&strcmp(argv[1], "z") && strcmp(argv[1], "i"))) { printf("Usage: %s [ p | v | q | z | i ]\n", argv[0]); printf("\tp: p operator\n"); printf("\tv: v operator\n"); printf("\tq: query semaphore value\n"); printf("\tz: z operator\n"); // z操作既不释放资源,也不申请资源,只做一个判断和等待信号量变为0 printf("\ti: init semaphore\n"); return -1; } key_t key; key = ftok("a", 1); if (key == -1) { perror("fail ftok"); return -1; } int semid; semid = semget(key, SEM_NUM, IPC_CREAT | 0664); if (semid == -1) { perror("fail semget"); return -1; } // 查询信号集内的各个信号量的值 if (argv[1][0] == 'q') { unsigned short array[SEM_NUM]; // 存放信号量的值 int i; semctl(semid, SEM_NUM, GETALL, array); printf("semaphore value:"); for (i = 0; i < SEM_NUM; i++) { printf(" %d", array[i]); } printf("\n"); } else { semop_PVZ(semid, argv[1][0]); } return 0; }
题目: