linux-C-信号量


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!
"); exit(1); } printf("create %d sem success!
",sem_id); // sem_val.val=1; rc=semctl(sem_id,0,SETVAL,sem_val);// ,0 ,1 ,... ;SETVAL if (rc==-1){ printf("initlize sem error!
"); exit(1); } // pid=fork(); if (pid==-1){ printf("fork error!
"); 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
",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
",i,get_sem_val(sem_id,0)); } } exit(0); }