命名管道实现进程间通信--石头、剪刀、布游戏 分类: linux ...

下面这个程序利用命名管道实现进程间通信,模拟石头剪刀布游戏。

主进程为裁判进程,两个子进程为选手进程。裁判与选手间各建立一个命名管道。

进行100次出招,最后给出游戏胜负。


#include <unistd.h>
#include<fcntl.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<stdlib.h>
#include<string.h>
#define FIFO1 "/tmp/myfifo1"
#define FIFO2 "/tmp/myfifo2"
#define SIZE 5
#define COUNT 100
int judge(char a,char b);
int main(void) 
{ 
 int fp,fp1,fp2,i=1;
 int status;
 int nread;
 char buf[SIZE]={0};
 char c1[COUNT]={0};//用来存放p1发送的消息
 char c2[COUNT]={0};//用来存放p2发送的消息
 pid_t p1 = fork(); //产生子进程p1
 /*********************************/
 if(p1==0)
 { 
  srand(time(NULL));
  while((fp=open(FIFO1,O_WRONLY|O_NONBLOCK))==-1);//只写打开管道1,不断尝试直到成功
  for(;i<=100;i++)
  {
    sprintf(b
  • 6
    点赞
  • 68
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个C语言实现石头剪刀布游戏,可以控制胜率的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int play, computer, winCount = 0, loseCount = 0, drawCount = 0; char choice; srand(time(NULL)); do { printf("请选择:\n"); printf("1. 石头\n"); printf("2. 剪刀\n"); printf("3. \n"); printf("0. 退出\n"); scanf("%d", &play); if (play == 0) { break; } computer = rand() % 3 + 1; printf("你选择了:"); switch (play) { case 1: printf("石头\n"); break; case 2: printf("剪刀\n"); break; case 3: printf("\n"); break; default: printf("无效选择\n"); continue; } printf("电脑选择了:"); switch (computer) { case 1: printf("石头\n"); break; case 2: printf("剪刀\n"); break; case 3: printf("\n"); break; } if (play == computer) { printf("平局!\n"); drawCount++; } else if ((play == 1 && computer == 2) || (play == 2 && computer == 3) || (play == 3 && computer == 1)) { printf("你赢了!\n"); winCount++; } else { printf("你输了!\n"); loseCount++; } printf("胜利次数:%d,失败次数:%d,平局次数:%d\n", winCount, loseCount, drawCount); printf("是否继续游戏?(y/n) "); scanf(" %c", &choice); } while (choice == 'y' || choice == 'Y'); return 0; } ``` 这个程序使用了随机数生成电脑的选择,然后根据玩家和电脑的选择进行比较,判断胜负或平局,并统计胜利、失败和平局的次数。你可以通过多次运行程序来控制胜率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值