deepfuture-lx@deepfuture-lx-desktop:~/private/mytest$ gcc -std=gnu99 -o testsem testsem.c
testsem.c: In function ‘get_sem_val’:
testsem.c:8: warning: implicit declaration of function ‘semctl’
testsem.c: In function ‘main’:
testsem.c:20: warning: implicit declaration of function ‘semget’
testsem.c:23: warning: implicit declaration of function ‘exit’
testsem.c:23: warning: incompatible implicit declaration of built-in function ‘exit’
testsem.c:31: warning: incompatible implicit declaration of built-in function ‘exit’
testsem.c:34: warning: implicit declaration of function ‘fork’
testsem.c:37: warning: incompatible implicit declaration of built-in function ‘exit’
testsem.c:44: warning: implicit declaration of function ‘semop’
testsem.c:58: warning: incompatible implicit declaration of built-in function ‘exit’
deepfuture-lx@deepfuture-lx-desktop:~/private/mytest$ ./testsem
create 65538 sem success!
0 生产者: 2
1 生产者: 3
2 生产者: 4
3 生产者: 5
4 生产者: 6
5 生产者: 7
6 生产者: 8
7 生产者: 9
8 生产者: 10
9 生产者: 11
10 生产者: 11
11 生产者: 12
12 生产者: 13
13 生产者: 14
14 生产者: 15
0 消费者: 11
1 消费者: 14
2 消费者: 13
3 消费者: 12
4 消费者: 11
5 消费者: 10
6 消费者: 9
7 消费者: 8
8 消费者: 7
9 消费者: 6
10 消费者: 5
11 消费者: 4
12 消费者: 3
13 消费者: 2
14 消费者: 1
deepfuture-lx@deepfuture-lx-desktop:~/private/mytest$
#include <stdio.h>
#include <linux/sem.h>
#define MAXNUMS 15
int get_sem_val(int sid,int semnum)//取得当前信号量
{
return(semctl(sid,semnum,GETVAL,0));
}
int main(void){
int sem_id;
int pid;
int rc;
struct sembuf sem_op;//信号集结构
union semun sem_val;//信号量数值
//建立信号量集,其中只有一个信号量
sem_id=semget(IPC_PRIVATE,1,IPC_CREAT|0600);//IPC_PRIVATE私有,只有本用户使用,如果为正整数,则为公共的;1为信号集的数量;
if (sem_id==-1){
printf("create sem error!\n");
exit(1);
}
printf("create %d sem success!\n",sem_id);
//信号量初始化
sem_val.val=1;
rc=semctl(sem_id,0,SETVAL,sem_val);//设置信号量,0为第一个信号量,1为第二个信号量,...以此类推;SETVAL表示设置
if (rc==-1){
printf("initlize sem error!\n");
exit(1);
}
//创建进程
pid=fork();
if (pid==-1){
printf("fork error!\n");
exit(1);
}
else if(pid==0){//一个子进程,消费者
for (int i=0;i<MAXNUMS;i++){
sem_op.sem_num=0;
sem_op.sem_op=-1;
sem_op.sem_flg=0;
semop(sem_id,&sem_op,1);//操作信号量,每次-1
printf("%d 消费者: %d\n",i,get_sem_val(sem_id,0));
}
}
else{//父进程,生产者
for (int i=0;i<MAXNUMS;i++){
sem_op.sem_num=0;
sem_op.sem_op=1;
sem_op.sem_flg=0;
semop(sem_id,&sem_op,1);//操作信号量,每次+1
printf("%d 生产者: %d\n",i,get_sem_val(sem_id,0));
}
}
exit(0);
}
2842

被折叠的 条评论
为什么被折叠?



