Linux 进程信号量

#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<pthread.h>
#include<sys/shm.h>
#include<memory.h>

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 main(){
    int shmid=shmget(30,sizeof(int),IPC_CREAT|0666);
    int* p=(int*)shmat(shmid,0,0);
    memset(p,0,sizeof(int));
    union semun sem;
    sem.val=1;
    struct sembuf pv[2]={{0,-1,0},{0,1,0}};
    
    int semid=semget(60,1,IPC_CREAT|0666);
    semctl(semid,0,SETVAL,sem);
    pid_t pid=fork();
    if(pid==0){
        semop(semid,pv,1);
        printf("sub read p %d\n",*p);
        sleep(5);
        semop(semid,&pv[1],1);
    }else if(pid>0){
        semop(semid,pv,1);
        *p=100;
        printf("main\n");
        sleep(5);
        semop(semid,&pv[1],1);
        wait(0);
    }



}

猜你喜欢

转载自www.cnblogs.com/libing029/p/10440197.html