我正在制作一个不同版本的猜谜游戏。这一次,子进程必须将它的猜测发送给父进程,然后父进程对其进行评估。我认为我做错的是我的孩子只跑了一次,但在找到正确的数字之前无法弄清楚如何猜测。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <sys/wait.h>
#include <time.h>
#define KEY 19950914
#define FLAG 0666
struct message {
long mtype;
int szam;
};
int main()
{
int number, false=1, guess=0;
int mqid;
struct message buf;
struct msqid_ds statbuff;
mqid = msgget(KEY, FLAG | IPC_CREAT);
if (mqid < 0)
perror("msgget"), exit(EXIT_FAILURE);
srand(time(NULL));
number = rand() % 256;
if (fork() == 0)
{
srand(time(NULL));
buf.mtype = 2;
buf.szam = rand() % 256;
msgsnd(mqid, &buf, sizeof(struct message), 0);
msgctl(mqid, IPC_STAT, &statbuff);
exit(EXIT_SUCCESS);
}
while ( guess != number )
{
if (guess > number)
printf("Too high!\n");
else if (guess < number)
printf("Too low!\n");
guess = msgrcv(mqid, &buf, sizeof(struct message), 2, 0);
}
printf("Winner! Yes, the answer was %d \n",number);
wait(NULL);
exit(EXIT_SUCCESS);
}