第一部分:创建semaphore,设置semaphore,最后进行v操作
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <string.h>
#include <stdlib.h>
int main(int argc,char* argv[])
{
key_t key = ftok("/home/kingoal/",3);
printf("Key: %d\n", key);
/**
* Create a single semaphore
*/
int sem_id = semget(key,1,IPC_CREAT|0660);
if(sem_id == -1)
{
perror("semget");
exit(-1);
}
printf("semaphore id: %d\n", sem_id);
/**
* Setting the value of semaphore
*/
union semun {
int value;
struct semid_ds* buf;
ushort* array;
}setting;
setting.value = 0;
int retcode = semctl(sem_id,0,SETVAL,setting);
if(retcode == -1)
{
perror("semctl");
exit(-1);
}
/**
* V operation on semaphore 0
*/
struct sembuf operations[1];
operations[0].sem_num = 0;
operations[0].sem_op = 2;
operations[0].sem_flg = 0;
retcode = semop(sem_id,operations,1);
if(retcode == -1)
{
perror("semop");
exit(-1);
}
printf("Increase the value of semaphore\n");
return 0;
}
第二部分: 查找对应的semaphore,然后对该semaphore进行p操作
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
int main(int argc,char* argv[])
{
key_t key = ftok("/home/kingoal/",3);
printf("Key: %d\n",key);
int sem_id = semget(key,1,0660);
if(sem_id == -1)
{
perror("semget");
exit(-1);
}
printf("Semaphore ID: %d\n",sem_id);
struct sembuf operations[1];
operations[0].sem_num = 0;
operations[0].sem_op = -1;
operations[0].sem_flg = 0;
int retcode = semop(sem_id,operations,1);
if(retcode == -1)
{
perror("semop");
exit(-1);
}
printf("Get the semaphore now\n");
return 0;
}
第三部分:下面是执行情况,有^C的表示阻塞了(处于waiting状态)
[kingoal@sunrise ~/dev/cxx]$ ipcs -as
Semaphores:
T ID KEY MODE OWNER GROUP CREATOR CGROUP NSEMS OTIME CTIME
s 196608 56308666 --rw-rw---- kingoal kingoal kingoal kingoal 1 23:14:33 21:18:21
[kingoal@sunrise ~/dev/cxx]$ ./semp
Key: 56308666
Semaphore ID: 196608
^C
[kingoal@sunrise ~/dev/cxx]$ ./semv
Key: 56308666
semaphore id: 196608
Increase the value of semaphore
[kingoal@sunrise ~/dev/cxx]$ ./semp
Key: 56308666
Semaphore ID: 196608
Get the semaphore now
[kingoal@sunrise ~/dev/cxx]$ ./semp
Key: 56308666
Semaphore ID: 196608
Get the semaphore now
[kingoal@sunrise ~/dev/cxx]$ ./semp
Key: 56308666
Semaphore ID: 196608
^C
[kingoal@sunrise ~/dev/cxx]$