码迷,mamicode.com
首页 > 其他好文 > 详细

c信号量操作demo

时间:2019-12-08 23:26:08      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:int   turn   flag   sign   perror   class   include   err   string   

#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/sem.h>

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

int P(int semid, int semnum) {
  struct sembuf sops={semnum, -1, SEM_UNDO};
  return (semop(semid, &sops, 1));
}

int V(int semid, int semnum) {
  struct sembuf sops = {semnum, +1, SEM_UNDO};
  return (semop(semid, &sops, 1));
}

void test2();

int main(int argc, char **argv){
  printf("argc:%d, argv:%s\n", argc, *argv);
  test2();
  return 0;
}

void test2(){
  int key;
  int semid,ret;
  union semun arg;
  struct sembuf semop;
  int flag;

  key = ftok("/tmp", 0x66);
  arg.val = 3;
  if (key < 0) {
    perror("ftok key error");
  }

  semid = semget(key, 3, IPC_CREAT | 0600);
  if(semid == -1) {
    perror("create semget error");
  }

  //对0号信号量设置为初始值
  ret = semctl(semid, 0, SETVAL, arg);
  printf("ret:%d\n", ret);
  if(ret < 0) {
    perror("ctl sem error");
    semctl(semid, 0, IPC_RMID, arg);
  }

  //取0号信号量的值
  ret = semctl(semid, 0, GETVAL, arg);
  printf("after semctl setval sem[0].val=[%d]\n", ret);
  
  //P操作
  flag = P(semid, 0);
  flag = P(semid, 0);
  ret = semctl(semid, 0, GETVAL, arg);
  printf("after P sem[0].val=[%d]\n",ret);

  //V操作
  if (V(semid, 0) < 0) {
    perror("V operator error");
  }
  if (V(semid, 0) < 0) {
    perror("V operator error");
  }
  ret = semctl(semid, 0, GETVAL, arg);
  printf("after v 操作 sem[0].val=%d\n", ret);
}

 

c信号量操作demo

标签:int   turn   flag   sign   perror   class   include   err   string   

原文地址:https://www.cnblogs.com/luckygxf/p/12008170.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!