linux信号量

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

int sem_creat(key_t key)
{
	int semid = 0;
	semid = semget(0x1111,1,0666|IPC_CREAT|IPC_EXCL);
	if(semid == -1)
	{
		perror("semget");
		if(errno == EEXIST)
		{
			printf("检测到信号量集已经存在\n");
			return 0;
		}
	}
	return semid;
}
int sem_open(key_t key)
{
	int semid = 0;
	semid = semget(0x1111,1,0666);
	if(semid == -1)
	{
		perror("semget");
		if(semid == -1)
		{
			perror("segment");
			return -1;
		}
	}
	return semid;
}
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) */
};	   
int sem_setval(int semid,int val)
{
	
	union semun su;
	su.val = val;
	int ret = semctl(semid,0,SETVAL,su);
	return ret;
}

int sem_getval(int semid)
{
	union semun su;
	int val =su.val;
	int ret = semctl(semid,0,SETVAL,su);
	printf("val:%d\n",val);
	return ret;
}
int sem_p(int semid)
{
	struct sembuf buf= {0,-1,0};
	int ret = semop(semid, &buf, 1);
	return ret;
	return 0;
}
int sem_v(int semid)
{
	struct sembuf buf= {0,1,0};
	int ret = semop(semid, &buf, 1);
	return ret;
}
int main()
{
	int semid;
	semid = sem_open(0x1111);
	sem_setval(semid,1);//当信号量小于0的时候会被阻塞
	sem_getval(semid);
	int pid = 0;
	pid = fork();
	sem_p(semid);
		int i = 0;
		printf("i :%d pid:%d \n",i++,getpid());
		sleep(3);
		printf("i :%d pid:%d \n",i++,getpid());
	sem_v(semid);
	return 0;
}

 

你可能感兴趣的:(Linux系统编程)