Posix有名信号量的基本操作

1. semcreate程序

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>           /* For O_* constants */
#include <sys/stat.h>        /* For mode constants */
#include <semaphore.h>

#define  FILE_MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)

int main(int argc, char** argv)
{
    int c, flags;
    sem_t *sem;
    unsigned int value;
    flags = O_RDWR | O_CREAT;
    value = 1;

    while((c = getopt(argc, argv, "e:")) != -1)
    {
        switch(c)
        {
            case 'e':
                flags != O_EXCL;
                break;

            case 'i':
                value = atoi(optarg);
                break;
        }
    }

    if(optind != argc - 1)
    {
        printf("usage: semcreate [ -e ] [ -i initalvalue] <name> ");
    }

    sem = sem_open(argv[optind], flags, FILE_MODE, value);

    sem_close(sem);

    exit(0);
}

2. semunlink程序

#include <semaphore.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char** argv)
{
    if(argc != 2)
    {
        printf("usage: semunlink <name>");
    }

    sem_unlink(argv[1]);

    exit(0);
}

3. semgetvalue程序

#include <unistd.h>
#include <stdio.h>
#include <semaphore.h>
#include <stdlib.h>

int main(int argc, char** argv)
{
    sem_t   *sem;
    int value;

    if(argc != 2)
    {
        printf("usage: semgetvalue <name>");
    }
    sem = sem_open(argv[1], 0);
    sem_getvalue(sem, &value);

    printf("value = %d\n", value);

    exit(0);
}

4.semwait程序

#include <stdio.h>
#include <unistd.h>
#include <semaphore.h>
#include <stdlib.h>

int main(int argc, char**argv)
{
    sem_t*  sem;
    int value;

    if(argc != 2)
    {
        printf("usage: semwait <name>");
    }
    sem = sem_open(argv[1], 0);
    sem_wait(sem);
    sem_getvalue(sem, &value);
    printf("pid %ld has semaphore, value = %d\n", (long)getpid(), value);
    
    pause();

    exit(0);
}

5.sempost程序

#include <stdio.h>
#include <unistd.h>
#include <semaphore.h>
#include <stdlib.h>

int main(int argc, char**argv)
{
    sem_t*  sem;
    int val;

    if(argc != 2)
    {
        printf("usage: sempost <name>");
    }
    sem = sem_open(argv[1], 0);

    sem_post(sem);

    sem_getvalue(sem, &val);

    printf("value = %d\n", val);

    exit(0);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值