用信号量实现进程互斥示例

代码:

#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <sys/sem.h>
#include <sys/wait.h>

union semun
{
    int val;
    struct semid_ds *buf;
    unsigned short *array;
}

int semid;

void sem_s(int semid)
{
    union semun sem_union;
    sem_union.val = 1;
    semctl(sem_id,0,SETVAL,sem_union);
}

void sem_d(int semid)
{
    union semun sem_union;
    semctl(sem_id,0,IPC_RMID,sem_union);
}

void sem_p(int semid)
{
    struct sembuf sem_b;
    sem_b = {0,-1,SEM_UNDO};
    semop(semid,&sem_b,1);
}

void sem_V(int semid)
{
    struct sembuf sem_b;
    sem_b = {0,1,SEM_UNDO};
    semop(semid,&sem_b,1);
}

void print(char op_char)
{
    int i;
    for(i=0; i<10; i++)
    {
        sem_p(semid);
        printf("%c",op_char);
        fflush(stdout);
        sleep(rand() % 3);
        printf("%c",op_char);
        fflush(stdout);
        sem_V(semid);
        sleep(rand() % 2);
    }
     
}

int main(int argc, char *argv[])
{
    semid = semget(1234,1,0666 | IPC_CREAT);
    sem_s(semid);
    pid_t pid;
    pid = fork();
    if(pid == -1)
        exit(EXIT_FAILURE);
    if(pid > 0)
    {
        print('o');
        wait(NULL);
        sem_d(semid);
    }
    else
    {
        print('x');
    }
        
    

    
    return 0;
}

 

posted @ 2017-03-30 16:33  ren_zhg1992  阅读(329)  评论(0)    收藏  举报