【发布时间】:2020-08-12 21:31:36
【问题描述】:
我正在制作一个不同版本的猜谜游戏。这一次,子进程必须将它的猜测发送给父进程,然后父进程对其进行评估。我认为我做错的是我的孩子只跑了一次,但在找到正确的数字之前无法弄清楚如何猜测。
#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);
}
【问题讨论】:
-
我强烈建议不要使用名为
false的变量。 -
为什么要将此问题标记为
bash?也许c会更合适? -
感谢您的关注。那是因为我用bash写代码,但确实是C文件。
-
msgsnd(mqid, &buf, sizeof(struct message)0);您的代码无法编译,因为该行有错字。请发布您实际运行的代码。 -
已更正,编辑时误删。
标签: c fork message-queue sysv-ipc msgrcv