arg2.val = MAXSHM; //初始时缓冲区中有5个空闲的数组元素 (emptyid, 缓冲区空信号量)
if(semctl(semid, 1, SETVAL, arg2) == -1)
{
perror("semctl setval error");
exit(1);
}
arg3.val = 1; //初始时互斥信号为1,允许一个进程进入 (mutexid, 互斥信号量)
if(semctl(semid, 2, SETVAL, arg3) == -1)
{
perror("semctl setval error");
exit(1);
}
/* 初始化 P, V操作 */
P.sem_num = 0;
P.sem_op = -1;
P.sem_flg = SEM_UNDO;
V.sem_num = 0;
V.sem_op = 1;
V.sem_flg = SEM_UNDO;
int i = 0;
while(i < 10)
{
P.sem_num = 1; //设置操作信号量emptyid
semop(semid, &P, 1); //对 emptyid执行P操作
P.sem_num = 2; //设置操作信号量mutexid
semop(semid, &P, 1); //对 mutexid执行 P操作
addr_c[i] = i + 'a';
printf("***addr_c[%d] = %c\n", i, addr_c[i]);
V.sem_num = 2; //设置操作信号量mutexid
semop(semid, &V, 1); //对mutexid执行 V 操作
V.sem_num = 0; //设置操作信号量fullid
semop(semid, &V, 1); //对fullid执行 V 操作
i++;
sleep(1);
}
sleep(60); //等待消费者进程退出
if(shmdt(addr_c) == -1)
{
perror("shmdt");
exit(1);
}
/* 删除共享内存区 */
if(shmctl(shmid, IPC_RMID, NULL) == -1)
{
perror("shmctl");
exit(1);
}
/* 撤消信号集 */
if(semctl(semid, 0, IPC_RMID, 0) == -1) //第三个参数cmd为IPC_RMID时,整个信号集被删除,第二个参数semnum被忽略。
{
perror("semctl");
exit(1);
}
return 0;
}
/*
*
* Filename: consumer.c
*
* Description: 消费者进程
*
* Version: 1.0
* Created: 09/30/2011 04:52:23 PM
* Revision: none
* Compiler: gcc(g++)
*
* Author: |Zhenghe Zhang|, |zhenghe.zhang@gmail.com|
* Company: |Shenzhen XXX Technology Co., Ltd.|
*
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#define MAXSHM 5 //定义缓冲区数组的下标变量个数
union semun {
int val; /* value for SETVAL */
struct semid_ds *buf;/* buffer for IPC_STAT & IPC_SET */
unsigned short *array;/* array for GETALL & SETALL */
struct seminfo *__buf;/* buffer for IPC_INFO */ //test!!
void *__pad;
};
int main()
{
key_t ipckey;
key_t semkey;
int shmid;
char *addr_c;
/* 定义信号灯集,该信号灯集包含3个信号量 fullid, emptyid, mutexid */
int semid;