Chinaunix首页 | 论坛 | 博客
  • 博客访问: 206921
  • 博文数量: 38
  • 博客积分: 2060
  • 博客等级: 大尉
  • 技术积分: 388
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-17 10:10
文章分类

全部博文(38)

文章存档

2011年(1)

2009年(37)

我的朋友

分类: LINUX

2009-08-21 11:25:45

相关函数具体情况请参考MAN手册,这里只是给出个演示
 
server:
 

#include <stdio.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/time.h>
#include <time.h>

int main(int argc, char **argv)
{
    int sem_no;
    key_t key;

    /*sem get*/
    key = ftok("/home/ddb/study/linux_c/ipc/sem/flag", 1);
    if((sem_no = semget(key, 1, IPC_CREAT | IPC_EXCL | 0644)) == -1)
    {
        printf("semget error! %s\n", strerror(errno));
    }

    /*sem ctl*/
    union semun {
            int val;
            struct demid_ds *buf;
            unsigned short *array;
            struct seminfo *__buf;
    }sem_un;
    sem_un.val = 1;
    if(semctl(sem_no, 0, SETVAL, sem_un) == -1)
    {
        printf("semctl failed! %s\n", strerror(errno));
    }

    /*sem op*/
    struct sembuf buf = {0};
    buf.sem_num = 0;
    buf.sem_op = -1;
    if(semop(sem_no, &buf, 1) == -1)
    {
        printf("semop failed! %s\n", strerror(errno));
    }
    sleep(5);
    buf.sem_op = 1;
    if(semop(sem_no, &buf, 1) == -1)
    {
        printf("semop2 failed! %s\n", strerror(errno));
    }
    /*del sem*/
    int ncnt;
    sleep(3);
    if((ncnt=semctl(sem_no, 0, GETNCNT)) == 0)
    {
        struct timeval time_buf = {0};
        struct timezone time_zone = {0};
        if(gettimeofday(&time_buf, &time_zone) == -1)
        {
            printf("gettimeofday failed! %s", strerror(errno));
        }
        sleep(20);
        if(semctl(sem_no, 0, IPC_RMID) == -1)
        {
            printf("rm sem failed! %s\n", strerror(errno));
        }
    }
    printf("---%d\n", ncnt);
    return 0;
}

 

client

 

#include <stdio.h>
#include <sys/types.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <errno.h>
#include <sys/time.h>
#include <time.h>

int main()
{
    int sem_no;
    key_t key;

    key = ftok("/home/ddb/study/linux_c/ipc/sem/flag", 1);
    if((sem_no = semget(key, 1, 0)) == -1)
    {
        printf("semget error! %s\n", strerror(errno));
    }

    struct sembuf buf = {0};
    buf.sem_num = 0;
    buf.sem_op = -1;
    buf.sem_flg = SEM_UNDO;
    if(semop(sem_no, &buf, 1) == -1)
    {
        printf("semop failed! %s\n", strerror(errno));
    }
    sleep(5);
    printf("-.-!!\n");

    buf.sem_op = 1;
    struct timeval time_buf = {0};
    struct timezone time_zone = {0};
    if(gettimeofday(&time_buf, &time_zone) == -1)
    {
        printf("gettimeofday failed! %s", strerror(errno));
    }

    printf("%s", ctime(&time_buf.tv_sec));
    if(semop(sem_no, &buf, 1) == -1)
    {
        printf("semop failed! %s%s\n", ctime(&time_buf.tv_sec), strerror(errno));
    }
    if(semctl(sem_no, 0, GETVAL) == -1)
    {
        printf("semctl failed! %s\n", strerror(errno));
    }
    return 0;
}

阅读(1061) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~