上篇概括了system V信号量基本使用,下面自己实现的一个简单的信号量代码:
#include <sys/sem.h>
#include <sys/ipc.h>
#include <unistd.h>
#include <time.h>
#include <stdio.h>
union semun {
int val;
struct semid_ds *buf;
short *array;
};
void child1(int semid);
void child2(int semid);
int main()
{
int ret;
pid_t pid1,pid2;
int semid1,semid2;
struct sembuf sem;
union semun sem_val;
if((semid1 = semget(IPC_PRIVATE,1,IPC_CREAT|0666)) < 0){
perror("semget semid1 error!\n");
}
if((semid2 = semget(IPC_PRIVATE,1,IPC_CREAT|0666)) < 0){
perror("semget semid2 erroe!\n");
}
sem_val.val = 0;
ret = semctl(semid1,0,SETVAL,sem_val);
if(ret < 0){
perror("semctl1 error!\n");
}
ret = semctl(semid2,0,SETVAL,sem_val);
if(ret < 0){
perror("semctl2 error!\n");
}
pid1 = fork();
if(pid1 < 0){
perror("fork pid1 error\n");
}
else if(pid1 == 0){
child1(semid1);
}
pid2 = fork();
if(pid2 < 0){
perror("fork pid2 error\n");
}
else if(pid2 == 0){
child2(semid2);
}
sem.sem_num = 0;
sem.sem_op = 1;
sem.sem_flg = SEM_UNDO;
while(1)
{
sleep(1);
if(semop(semid1,&sem,1) == -1){
perror("semop semid1\n");
}
if(semop(semid2,&sem,1) == -1){
perror("semop semid2\n");
}
}
return 0;
}
void child1(int semid1)
{
struct sembuf sem1;
sem1.sem_num = 0;
sem1.sem_op = -1;
sem1.sem_flg = SEM_UNDO;
while(1)
{
if(semop(semid1,&sem1,1) == -1){
perror("semop semid1\n");
}
printf("this is the child1\n");
sleep(1);
}
}
void child2(int semid2)
{
struct sembuf sem2;
sem2.sem_num = 0;
sem2.sem_op = -5;
sem2.sem_flg = SEM_UNDO;
while(1)
{
if(semop(semid2,&sem2,1) == -1){
perror("semop semid2\n");
}
printf("this is the child2\n");
sleep(1);
}
}
运行结果如下:this is the child1this is the child1this is the child1this is the child1this is the child1this is the child2this is the child1this is the child1this is the child1this is the child1this is the child1this is the child2
本文仅限学习之用,如有雷同不胜荣幸!!有误之处请指出,谢谢合作!