IPC--信号量 Semaphore 生产者 消费者模型 (semget semop semctl)


/*
 * producer.c
 *
 *  Created on: 2011-11-19
 *      Author: snape
 */

#include <stdio.h>
#include <sys/sem.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char **argv) {
	void say(int, char*);
	int semid;
	struct sembuf buf;
	say((semid = semget(1000, 2, 0666)) < 0, "open semaphore 1000");
	buf.sem_num = 0;
	buf.sem_op = -1;
	buf.sem_flg = buf.sem_flg & ~IPC_NOWAIT;

	say(semop(semid, &buf, 1) < 0, "P semaphore 1000 : 0");

	fprintf(stderr, "[%d]producing...\n", getpid());
	sleep(1);
	fprintf(stderr, "[%d]produced\n", getpid());

	buf.sem_num = 1;
	buf.sem_op = 1;
	buf.sem_flg = buf.sem_flg & ~IPC_NOWAIT;

	say(semop(semid, &buf, 1) < 0, "V semaphore 1000 : 1");

	return 0;
}

void say(int flag, char * str) {
	if (flag) {
		fprintf(stderr, "%s fail\n", str);
		exit(1);
	} else {
		fprintf(stderr, "%s success\n", str);
	}
}



/*
 * consumer.c
 *
 *  Created on: 2011-11-19
 *      Author: snape
 */
#include <stdio.h>
#include <sys/sem.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char **argv) {
	void say(int, char*);
	int semid;
	struct sembuf buf;
	say((semid = semget(1000, 2, 0666)) < 0, "open semaphore 1000");

	buf.sem_num = 1;
	buf.sem_op = -1;
	//设置操作方式为 阻塞
	buf.sem_flg = buf.sem_flg & ~IPC_NOWAIT;

	say(semop(semid, &buf, 1) !=  0, "P semaphore 1000:1");
	fprintf(stderr, "[%d]consuming...\n", getpid());
	sleep(1);

	fprintf(stderr, "[%d]consumed...\n", getpid());

	buf.sem_num = 0;
	buf.sem_op = 1;
	buf.sem_flg = buf.sem_flg & ~IPC_NOWAIT;
	say(semop(semid, &buf, 1) != 0, "V semaphore 1000:0");

	return 0;
}

void say(int flag, char * str) {
	if (flag) {
		fprintf(stderr, "%s fail\n", str);
		exit(1);
	} else {
		fprintf(stderr, "%s success\n", str);
	}
}

执行前需要使用semctl函数初始化设置信号量的值。如 1000:0 为5,1000:1为0

你可能感兴趣的:(IPC--信号量 Semaphore 生产者 消费者模型 (semget semop semctl))