使用三个程序来完成输出ABCABCABCABCABC
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/sem.h>
#define NUM_SEMS 3 // 信号量集中的信号量数量
union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
struct seminfo *__buf;
};
void P(int semid, int sem_num) {
struct sembuf semaphore;
semaphore.sem_num = sem_num;
semaphore.sem_op = -1;
semaphore.sem_flg = 0;
semop(semid, &semaphore, 1);
}
void V(int semid, int sem_num) {
struct sembuf semaphore;
semaphore.sem_num = sem_num;
semaphore.sem_op = 1;
semaphore.sem_flg = 0;
semop(semid, &semaphore, 1);
}
int main() {
// 创建信号量集
int semid = semget(IPC_PRIVATE, NUM_SEMS, IPC_CREAT | 0666);
if (semid == -1) {
perror("semid error");
return 1;
}
union semun sem_union;
// 初始化信号量
for (int i = 0; i < NUM_SEMS; i++) {
sem_union.val = (i == 0) ? 1 : 0; // 设置第一个信号量为1,其他为0
if (semctl(semid, i, SETVAL, sem_union) == -1) {
perror("semctl error");
return 1;
}
}
int pidA, pidB, pidC;
char sem_chars[] = {'A', 'B', 'C'};
for (int i = 0; i < 5; i++) {
// 创建A进程
pidA = fork();
if (pidA == 0) {
P(semid, 0);
printf("A");
V(semid, 1);
return 0;
}
// 创建B进程
pidB = fork();
if (pidB == 0) {
P(semid, 1);
printf("B");
V(semid, 2);
return 0;
}
// 创建C进程
pidC = fork();
if (pidC == 0) {
P(semid, 2);
printf("C");
V(semid, 0);
return 0;
}
}
// 父进程等待子进程结束
waitpid(pidA, NULL, 0);
waitpid(pidB, NULL, 0);
waitpid(pidC, NULL, 0);
// 删除信号量集
if (semctl(semid, 0, IPC_RMID) == -1) {
perror("delete error:");
return 1;
}
printf("\n");
return 0;
}
运行效果:
思维导图