父节点有m个消息要发送给n个子节点。在每次迭代中,它向所有子节点发送一条消息。如果所有子节点都回复“收到”,它将发送下一条消息。下面是我的代码
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX_LEN 50
struct details
{
int no;
int id;
char msg_text[MAX_LEN];
};
typedef struct msg_buf
{
long int msg_type;
struct details d;
} msg;
char message[20][50] =
{
" ",
"Message1",
"Message2",
"Message3",
"Message4",
"Message5",
"Message6",
"Message7",
"Message8"
};
int main(int argc, char *argv[])
{
int id1, id2, n, m, i, j, status, p_id;
pid_t pid;
msg snd, rcvd;
if (argc < 2)
{
perror("Too few arguments");
return -1;
}
n = atoi(argv[1]);
m = atoi(argv[2]);
id1 = msgget((key_t)78, IPC_CREAT | 0666);
id2 = msgget((key_t)56, IPC_CREAT | 0666);
if (id1 == -1 || id2 == -1)
{
printf("Error in creating message queue\n");
return -1;
}
p_id = getpid();
printf("\nQueues are created.\n\n");
for (i = 1; i <= n; i++)
{
pid = fork();
if (pid == 0)
break;
}
if (pid == 0)
{
for (j = 1; j <= m; j++)
{
printf("Process %d waiting for message %d\n", getpid(), j);
while (msgrcv(id1, &rcvd, sizeof(struct details), j + 1, IPC_NOWAIT) < 0)
{
}
srand(time(0));
strcpy(snd.d.msg_text, "Received");
snd.msg_type = rcvd.msg_type;
snd.d.no = rcvd.d.no;
snd.d.id = getpid();
if (msgsnd(id2, &snd, sizeof(struct details), IPC_NOWAIT) < 0)
{
perror("msgsnd");
}
else
{
printf("Reply sending successful for message %d for process %d\n", snd.d.no, snd.d.id);
}
}
}
if (p_id == getpid())
{
for (j = 1; j <= m; j++)
{
strcpy(snd.d.msg_text, message[j]);
snd.msg_type = j + 1;
snd.d.no = j;
if (msgsnd(id1, &snd, sizeof(struct details), 0) < 0)
{
perror("msgsnd");
}
else
{
printf("Message %d sent- \t\t\t\t%s\n", j, snd.d.msg_text);
}
for (i = 1; i <= n; i++)
{
sleep(i);
if (msgrcv(id2, &rcvd, sizeof(struct details), j + 1, 0) >= 0)
{
printf("Reply received from child %d for message %d - \t%s\n", rcvd.d.id, j, rcvd.d.msg_text);
}
}
}
wait(NULL);
printf("Communication End.\n\n");
}
}
对于n=2,m=2,我得到的输出是:
Queues are created.
Message 1 sent- Message1
Process 14804 waiting for message 1
Process 14805 waiting for message 1
Reply sending successful for message 1 for process 14804
Process 14804 waiting for message 2
Reply received from child 14804 for message 1 - Received
在此之后什么也没有打印出来。没有进展。问题是什么?如何解决这个问题?
1条答案
按热度按时间zpqajqem1#
最大的一个问题是在评论中提到的一个问题:
AFAICS,每次迭代发送一条消息,所以最多一个孩子可以阅读它。
任何给定的消息最多只能被一个进程接收。要让
n
进程接收消息,您必须发送n
消息。其他问题大多是表面文章。(Stack Overflow Questions)repository on GitHub as files
stderr.c
andstderr.h
in src/libsoq subdirectory. Some of the messages are written tostdout
- there is not a function that takes just a file stream,so I usederr_logmsg()
which takes a file stream,控制选项和退出状态(但函数不应该退出,因此未使用)以及格式和参数。结果是:
有大量的日志记录,因为我需要查看发生了什么。代码应该(但不)验证
n
和m
的值。它们应该至少是1
,不超过一些稍微正常的数字(例如10
),但会有一个或两个值-枚举或定义的常量-以限制可接受的范围。下面是一个示例输出(源代码
msg79.c
,程序msg79
):