信号量(Semphore)
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/sem.h>
union semun
{
int val;
struct semid_ds *buf;
unsigned short *arry;
};
static int sem_id = 0;
static int set_semvalue();
static void del_semvalue();
static int semaphore_p();
static int semaphore_v();
int main(int argc, char *argv[])
{
char message = 'X';
int i = 0;
// 创建信号量
sem_id = semget((key_t)1234, 1, 0666|IPC_CREAT);
if (argc > 1)
{
// 程序第一次被调用,初始化信号量
if (!set_semvalue())
{
fprintf(stderr, "Failed to initialize semaphore.\n");
exit(EXIT_FAILURE);
}
// 设置要输出到屏幕中的信息,及其参数的第一个字符
message = argv[1][0];
}
for (i = 0; i < 10; ++i)
{
// 进入临界区
if (!semaphore_p())
exit(EXIT_FAILURE);
// 向屏幕中输出数据
printf("%c", message);
// 清理缓冲区&