鱼C论坛

 找回密码
 立即注册
查看: 1128|回复: 2

[学习笔记] 自学linux.信号量实验

[复制链接]
发表于 2022-7-10 19:37:13 From FishC Mobile | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/sem.h>


#define KEY (key_ t)14010322
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 void semaphore_ p();
static void semaphore_ _v();
int main(int argc, char *argv[]) {
int semid;
int product= 1;
int i;
if(-1 == (semid = semget(KEY,3,IPC_ _CREAT|0660))) {
print("ERROR\n");
gso
return -1;
(138
union semun arg[3];
arg[0].val= 1; //mutex= 1;
arg[1].val= 5; //empty= 5;
arg[2].val= 0; //full= 0;
for(i=0;i<3;i++){
semctl(semid, i, SETVAL, arg[i]); .
for(i=0;i < 3;i++){
printf("The semval(%d) = %d\n",i,semctl(semid,i,GETVAL,NUL);
}
pid_ t p1,p2;
if(0 == (p1 = fork()){
while(1) {
semaphore_ p(semid,1);//P(empty)
printf("1\n");
semaphore_ .p(semid,0);//P(mutex)
printf("2\n");
product++;
printf("Producer %d: %d things",getpid(),product);
semaphore_ _v(semid,0);//V(mutex);
semaphore_ v(semid,2);//N(ul);
sleep(2);
}
}else {
if(0 == (p2 = fork()){
while(1){
sleep(2);
semaphore_ p(semid,2);// p(full)
printf("3\n");
semaphore_ .p(semid,0);//p(mutex)
printf("4\n");
product--;
printf("Consumer1 %d: %d things' ',getpid(),product);
semaphore_ v(semid,0);
semaphore_ _v(semid,1);
sleep(5);
}
}else{
while(1){
sleep(2);
semaphore_ .p(semid,2);//p(ulI)
printf("5\n");
semaphore_ _p(semid,0);//p(mutex)
printf("6\n");
product--; .
printf("Consumer2 %d: %d things ',getpid()product);
semaphore_ _v(semid,0);
semaphore_ v(semid,1);
sleep(5);
}
}
}
}
static void del_ semvalue() {
union semun sem_ union;
if(-1 == semctl(sem_ _id, 0, IPC_ RMID, sem_ union))
fprintf(stderr, "Failed to delete semaphore\n");
}
static int set_ semvalue() {
union semun sem_ union;
sem_ union.val= 1;
if(-1 == semctl(sem_ id, 0, SETVAL, sem_ _union))
return 0;
9
return 1;

}
x1
void semaphore_ .p(int sem_ id, int semNum) {
struct sembuf sem_ b;
sem_ b.sem_ num = semNum;
sem_ b.sem_ _op= -1; //P()
sem_ _b.sem_ _flg = SEM_ UNDO;
if (-1 == semop(sem_ id, &sem_ b, 1)) {
fprintf(stderr, "semaphore_ p failed\n");
}
}
void semaphore_ _v(int sem_ id, int semNum) {
struct sembuf sem_ b;
sem b.sem num = semNum;
sem_ b.sem_ op= 1; //N()
sem_ _b.sem_ _flg = SEM_ UNDO;
if(-1 == semop(sem_ id, &sem_ _b, 1)) {
fprintf(stderr, "semaphore_ p failed\n");
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-7-10 19:43:00 | 显示全部楼层
哇,这代码格式
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-7-10 19:51:20 | 显示全部楼层
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-28 17:03

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表