编写C程序,使用Linux中的IPC机制,完成 “石头、剪子、布”的游戏。
时间: 2024-05-01 22:19:18 浏览: 60
这个游戏可以使用共享内存和信号量来实现进程间通信。下面是一个简单的实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <time.h>
#define SHM_KEY 1234
#define SEM_KEY 5678
#define ROCK 0
#define PAPER 1
#define SCISSORS 2
void play(int choice);
int main() {
int shmid, semid;
int *shmaddr;
union semun {
int val; /* value for SETVAL */
struct semid_ds *buf; /* buffer for IPC_STAT & IPC_SET */
unsigned short *array; /* array for GETALL & SETALL */
struct seminfo *__buf; /* buffer for IPC_INFO */
} arg;
/* 创建共享内存 */
shmid = shmget(SHM_KEY, sizeof(int), IPC_CREAT | 0666);
if (shmid < 0) {
perror("shmget");
exit(1);
}
/* 连接共享内存 */
shmaddr = shmat(shmid, NULL, 0);
if (shmaddr == (int *) -1) {
perror("shmat");
exit(1);
}
/* 创建信号量 */
semid = semget(SEM_KEY, 1, IPC_CREAT | 0666);
if (semid < 0) {
perror("semget");
exit(1);
}
/* 初始化信号量 */
arg.val = 1;
if (semctl(semid, 0, SETVAL, arg) < 0) {
perror("semctl");
exit(1);
}
/* 游戏开始 */
printf("Welcome to the game of rock-paper-scissors!\n");
printf("Enter 0 for rock, 1 for paper, or 2 for scissors.\n");
printf("Enter -1 to quit the game.\n");
while (1) {
int choice;
printf("Your choice:");
scanf("%d", &choice);
if (choice == -1) {
break;
}
if (choice < 0 || choice > 2) {
printf("Invalid choice.\n");
continue;
}
play(choice);
printf("The result is %d.\n", *shmaddr);
}
/* 删除共享内存 */
if (shmdt(shmaddr) < 0) {
perror("shmdt");
exit(1);
}
if (shmctl(shmid, IPC_RMID, NULL) < 0) {
perror("shmctl");
exit(1);
}
/* 删除信号量 */
if (semctl(semid, 0, IPC_RMID, arg) < 0) {
perror("semctl");
exit(1);
}
return 0;
}
void play(int choice) {
int shmid, semid;
int *shmaddr;
struct sembuf sops;
/* 连接共享内存 */
shmid = shmget(SHM_KEY, sizeof(int), 0666);
if (shmid < 0) {
perror("shmget");
exit(1);
}
shmaddr = shmat(shmid, NULL, 0);
if (shmaddr == (int *) -1) {
perror("shmat");
exit(1);
}
/* 连接信号量 */
semid = semget(SEM_KEY, 1, 0666);
if (semid < 0) {
perror("semget");
exit(1);
}
/* 等待信号量 */
sops.sem_num = 0;
sops.sem_op = -1;
sops.sem_flg = SEM_UNDO;
if (semop(semid, &sops, 1) < 0) {
perror("semop");
exit(1);
}
/* 生成随机数 */
srand(time(NULL));
int computer = rand() % 3;
/* 比较选择 */
int result;
if (choice == computer) {
result = 0;
} else if ((choice == ROCK && computer == SCISSORS) ||
(choice == PAPER && computer == ROCK) ||
(choice == SCISSORS && computer == PAPER)) {
result = 1;
} else {
result = -1;
}
/* 将结果写入共享内存 */
*shmaddr = result;
/* 释放信号量 */
sops.sem_op = 1;
if (semop(semid, &sops, 1) < 0) {
perror("semop");
exit(1);
}
/* 断开共享内存 */
if (shmdt(shmaddr) < 0) {
perror("shmdt");
exit(1);
}
}
```
这个程序使用了一个共享内存来存储每次游戏的结果,以及一个信号量来保证同一时刻只有一个进程可以访问共享内存。每个进程调用 `play` 函数来进行游戏,并将结果写入共享内存。主进程读取共享内存中的结果并输出。