Permalink
Find file
Fetching contributors…
Cannot retrieve contributors at this time
68 lines (57 sloc) 1.48 KB
#ifndef _SHMDATA_H_HEADER
#define _SHMDATA_H_HEADER
#include <stdio.h>
#include <sys/sem.h>
#include <sys/types.h>
#include <errno.h>
#define TEXT_SZ 2048
struct shared_msg
{
int isWritten;//作为一个标志,非0:表示可读,0表示可写 1表示已经写完,可以读,0表示可写
char msg[TEXT_SZ];//记录写入和读取的文本
};
static int set_semvalue(int sem_id)
{
//用于初始化信号量,在使用信号量前必须这样做
union semun sem_union;
sem_union.val = 1;
if(semctl(sem_id, 0, SETVAL, sem_union) == -1)
return 0;
return 1;
}
static void del_semvalue(int sem_id)
{
//删除信号量
union semun sem_union;
if(semctl(sem_id, 0, IPC_RMID, sem_union) == -1)
fprintf(stderr, "Failed to delete semaphore\n");
}
static int semaphore_p(int sem_id)
{
//对信号量做减1操作,即等待P(sv)
struct sembuf sem_b;
sem_b.sem_num = 0;
sem_b.sem_op = -1;//P()
sem_b.sem_flg = SEM_UNDO;
if(semop(sem_id, &sem_b, 1) == -1)
{
fprintf(stderr, "semaphore_p failed\n");
return 0;
}
return 1;
}
static int semaphore_v(int sem_id)
{
//这是一个释放操作,它使信号量变为可用,即发送信号V(sv)
struct sembuf sem_b;
sem_b.sem_num = 0;
sem_b.sem_op = 1;//V()
sem_b.sem_flg = SEM_UNDO;
if(semop(sem_id, &sem_b, 1) == -1)
{
fprintf(stderr, "semaphore_v failed\n");
return 0;
}
return 1;
}
#endif