这里的信号量主要是在不同的进程之间使用。
需要四个操作
因为库里没有定义union semun,因此需要自己定义.
用到信号量的三个函数
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<sys/sem.h>
union semun
{
int val;
struct semid_ds *buf;
unsigned short int *array;
struct seminfo *__buf;
};
static int set_semvalue(void);
static void del_semvalue(void);
static int semaphore_p(void);
static int semaphore_v(void);
static int sem_id;
static int set_semvalue(void)
{
union semun sem_union;
sem_union.val=1;
semctl(sem_id,0,SETVAL,sem_union);
}
static void del_semvalue(void)
{
union semun sem_union;
semctl(sem_id,0,IPC_RMID,sem_union);
}
static int semaphore_p(void)
{
struct sembuf sem_b;
sem_b.sem_num=0;
sem_b.sem_op=-1;
sem_b.sem_flg=SEM_UNDO;//auto release
semop(sem_id,&sem_b,1);
}
static int semaphore_v(void)
{
struct sembuf sem_b;
sem_b.sem_num=0;
sem_b.sem_op=1;
sem_b.sem_flg=SEM_UNDO;//auto release
semop(sem_id,&sem_b,1);
}
//main function
int main(int argc,char *agrv[])
{
int i;
int pause_time;
char op_char=‘O‘;
srand((unsigned int)getpid());
sem_id=semget((key_t)1234,1,0666|IPC_CREAT);
if(argc>1)
{
set_semvalue();
op_char=‘X‘;
sleep(2);
}
for(i=0;i<10;i++)
{
semaphore_p();
printf("%c",op_char);
fflush(stdout);
pause_time=rand()%3;
sleep(pause_time);
printf("%c",op_char);
fflush(stdout);
semaphore_v();
pause_time=rand()%2;
sleep(pause_time);
}
printf("\n%d - finished\n",getpid());
if(argc>1)
{
sleep(10);
del_semvalue();
}
exit(0);
}
jiang@ubuntu:~/myTest./sem1 1 &
[1] 12839
jiang@ubuntu:~/myTest ./sem1
OOXXOOXXOOXXOOXXOOXXXXOOXXOOXXOOXXOOXXOO
12839 - finished
12840 - finished
jiang@ubuntu:~/myTest$
原文地址:http://blog.csdn.net/u013011841/article/details/43658949