#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#define SEM_KEY 0x1234
#define MAX_COUNT 10
void P(int semID);
void V(int semID);
union semun {
int val;
struct semid_ds *buf;
ushort *array;
};
int main() {
int semID, i, pid;
union semun sem_union;
// 创建信号量
semID = semget(SEM_KEY, 1, IPC_CREAT | 0666);
if (semID == -1) {
perror("semget failed");
exit(EXIT_FAILURE);
}
// 初始化信号量值为1
sem_union.val = 1;
if (semctl(semID, 0, SETVAL, sem_union) == -1) {
perror("semaphore initialization failed");
exit(EXIT_FAILURE);
}
for (i = 0; i < 2; i++) {
pid = fork();
if (pid == 0 || pid == -1) {
break;
}
}
if (pid == -1) {
perror("fork failed");
exit(EXIT_FAILURE);
}
if (pid == 0) { // 子进程1和子进程2
for (i = 1; i <= MAX_COUNT; i++) {
P(semID);
// 子进程1打印son,子进程2打印daughter
printf("%s %d\n", (i == 0) ? "son" : "daughter", i);
fflush(stdout);
V(semID);
sleep(1);
}
exit(EXIT_SUCCESS); // 子进程执行完成后退出
} else {
// 父进程的打印任务
for (i = 1; i <= MAX_COUNT; i++) {
P(semID);
printf("parent %d\n", i);
fflush(stdout);
V(semID);
sleep(1);
}
// 等待子进程结束
while (wait(NULL) > 0);
// 销毁信号量
if (semctl(semID, 0, IPC_RMID, sem_union) == -1) {
perror("Failed to delete semaphore");
}
exit(EXIT_SUCCESS);
}
}
void P(int semID) {
struct sembuf sop;
sop.sem_num = 0;
sop.sem_op = -1; // P操作
sop.sem_flg = SEM_UNDO;
if (semop(semID, &sop, 1) == -1) {
perror("P operation failed");
exit(EXIT_FAILURE);
}
}
void V(int semID) {
struct sembuf sop;
sop.sem_num = 0;
sop.sem_op = 1; // V操作
sop.sem_flg = SEM_UNDO;
if (semop(semID, &sop, 1) == -1) {
perror("V operation failed");
exit(EXIT_FAILURE);
}
}