semaphore (freebsd)系统调用与例子

第一部分:创建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]$ 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值