| 
 | 
 
 
发表于 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"); 
} |   
 
 
 
 |