首页新闻找找看学习计划

关于在Linux 环境编程的问题

0
悬赏园豆:10 [已关闭问题] 关闭于 2016-05-26 23:15

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <fcntl.h>

#define SEM_KEY "./4-process_sem.c"
typedef union Semun{
        int             val;
        struct semid_ds *buf;
        unsigned short  *array;
}semun;

inline void err_que(const char *msg)
{
        puts(msg);
        exit(0);
}

inline void err_sys(const char *msg, int key)
{
        printf("%s : %s\n", msg, strerror(errno));
        semctl(key, 0, IPC_RMID);
        exit(0);
}

void show_sem(int sem_id, int senum);

int main()
{
        key_t sem_key;
        pid_t pid;
        semun arg;
        int sem_id;
        short sem_val[2] = {10, 20};

        if((sem_key = ftok(SEM_KEY, 433))       == -1)                  // 创建一个键
                err_que("sem_key error");

        if(sem_id = semget(sem_key, 2,IPC_CREAT|0660) == -1)    // 创建信号量集
                err_sys("semget error", sem_id);

        arg.array = sem_val;
        if(semctl(sem_id, 0, SETALL, &arg) == -1)
                err_sys("sem_ctl error", sem_id);

        show_sem(sem_id, 0);

        return 0;
}


void show_sem(int sem_id, int semnum)
{
        semun arg;

        arg.buf = (struct semid_ds *)malloc(sizeof(struct semid_ds));
/*
        if(semctl(sem_id, semnum, IPC_STAT, arg) == -1)
                err_sys("semctl1 error");

        printf("sem_nsems : %d\n", arg.buf->sem_nsems);
        printf("sem_otime : %d\n", arg.buf->sem_otime);
        printf("sem_ctime : %d\n", arg.buf->sem_ctime);*/
        printf("semval    : %d\n", semctl(sem_id, semnum, GETVAL));
        printf("sempid    : %d\n", semctl(sem_id, semnum, GETPID));
        printf("semncnt   : %d\n", semctl(sem_id, semnum, GETNCNT));
        printf("semzcnt   : %d\n", semctl(sem_id, semnum, GETZCNT));
/*
        if(semctl(sem_id, semnum, GETALL, &arg) == -1)
                err_sys("semctl2 error");

        printf("semall : %3d|%3d\n", arg.array[0], arg.array[1]);
*/
}

莫小川的主页 莫小川 | 初学一级 | 园豆:94
提问于:2015-11-29 23:12
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册