有名信号量的创建

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <semaphore.h>

const int maxline=4096;

int main(int argc, char **argv) {
	int c, flags;
	sem_t *sem;
	unsigned int value;
	char errbuff[maxline];

	flags = O_RDWR | O_CREAT;
	value=1;

	while((c=getopt(argc, argv, "ei:"))!=-1) {
		switch(c) {
		case 'e':
			flags|=O_EXCL;
			break;
		case 'i':
			value=atoi(optarg);
			break;
		}
	}
	
	if(optind!=argc-1) {
		fprintf(stderr, "usage: ./a.out [-e] [-i initalvalue] <name>.\n");
		exit(-1);
	}

	if((sem=sem_open(argv[optind], flags, 0644, value))==SEM_FAILED) {
		strerror_r(errno, errbuff, maxline);
		fprintf(stderr, "sem_open error: %s\n", errbuff);
		exit(-1);
	}

	sem_close(sem);

	exit(0);
}

查看创建结果:

$ ./a.out jia
$ cd /dev/shm/
$ ls -l
total 4
-rw-r--r--. 1 dmin dmin 32 Oct 11 14:19 sem.jia

 获取信号量的值:

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

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

	if(argc!=2) {
		fprintf(stderr, "usage: ./a.out <name>.\n");
		exit(-1);
	}

	sem=sem_open(argv[1], 0);
	sem_getvalue(sem, &val);

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

	exit(0);
}

结果如下:

$ ./a.out jia
value=1

  

posted @ 2022-10-11 14:22  东宫得臣  阅读(26)  评论(0编辑  收藏  举报