1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <sys/wait.h> #include <unistd.h>
#define ROCK 0 #define PAPER 1 #define SCISSORS 2
struct Game { long type; int round; };
void result_send(int msgid) { struct Game game; game.type = 1; game.round = rand() % 3; msgsnd(msgid, &game, sizeof(int), 0); }
int result_announce(int a, int b) { if ((a + 1) % 3 == b) return -1; else if (a == b) return 0; else return 1; }
void print_results(int *result_list, int len) { int countA = 0, countB = 0, pingju = 0; for (int i = 0; i < len; i++) { switch (result_list[i]) { case -1: countA++; printf("NO.%d:A win\n", i + 1); break; case 0: pingju++; printf("NO.%d:end in a draw\n", i + 1); break; case 1: countB++; printf("NO.%d:B win\n", i + 1); break; } } printf("The final result is A win:%ds\nB win:%ds\nend in a draw %ds\n", countA, countB, pingju); }
int main() { int times; printf("Game start, please input rounds: "); scanf("%d", ×);
int *result_list = (int*)malloc(times * sizeof(int)); int msgid1 = msgget(1234, IPC_CREAT | 0666); int msgid2 = msgget(5678, IPC_CREAT | 0666);
pid_t pid1 = fork(); if (pid1 == 0) { srand(time(NULL) * 3000); for (int i = 0; i < times; i++) result_send(msgid1); exit(0); }
pid_t pid2 = fork(); if (pid2 == 0) { srand(time(NULL)); for (int i = 0; i < times; i++) result_send(msgid2); exit(0); }
wait(NULL); wait(NULL);
for (int i = 0; i < times; i++) { struct Game game1, game2; msgrcv(msgid1, &game1, sizeof(int), 0, 0); msgrcv(msgid2, &game2, sizeof(int), 0, 0); result_list[i] = result_announce(game1.round, game2.round); }
print_results(result_list, times);
msgctl(msgid1, IPC_RMID, 0); msgctl(msgid2, IPC_RMID, 0);
free(result_list);
return 0; }
|