本次主要写了两个程序,一个用于对信号量进行p操作,一个用于进行v操作。p操作导致资源阻塞时,必须等待v操作释放资源。
p操作代码如下:
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <string.h> #include <signal.h> int semId; int SIZE = 1; union semun { int val; /* Value for SETVAL */ struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */ unsigned short *array; /* Array for GETALL, SETALL */ struct seminfo *__buf; /* Buffer for IPC_INFO (Linux-specific) */ }; void Handle(int s){ if(s == 2){ semctl(semId,0,IPC_RMID); exit(0); } } int main(){ signal(2,Handle); key_t key = ftok(".",4); semId = semget(key,1,IPC_CREAT | IPC_EXCL | 0666); union semun v; v.val = SIZE; if(semctl(semId,0,SETVAL,v) == -1){ printf("semctl error!\n"); exit(0); } struct sembuf sop; sop.sem_num = 0; sop.sem_op = -1; sop.sem_flg = 0; while(1){ semop(semId,&sop,1); printf("go go go!!!\n"); sleep(1); } return 0; }
v操作代码如下:
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <string.h> #include <signal.h> int semId; int main(){ key_t key = ftok(".",4); semId = semget(key,0,0); struct sembuf sop; sop.sem_num = 0; sop.sem_op = 1; sop.sem_flg = 0; while(1){ if(semop(semId,&sop,1) == -1) exit(0); sleep(1); } return 0; }
运行结果如下: