c - 发送和接收
问题描述
我有一个任务,我必须创建多个队列。目前我被卡住了,因为我不明白如何将消息发送到特定队列以及如何将输入的消息发送/接收到该特定队列。这是我写的代码:
typedef struct _node {
const char *message;
struct _node *next;
} node_t;
解决方案
我认为这段代码会产生预期的行为:
typedef struct msg_queue_node {
char * message;
struct msg_queue_node * next;
} msg_queue_node_t;
typedef struct msg_queue {
msg_queue_node_t * head, * tail;
} msg_queue_t;
int main(void)
{
int i, id; // indentifies the message queue in the array
msg_queue_t * msg_queues = malloc(NUM_QUEUES * sizeof(msg_queue_t*));
for (i = 0; i < NUM_QUEUES; i++)
msg_queues[i] = createQ();
// ...
while ( /*condition*/ ) {
scanf("%c %d", choice, id);
switch (choice) {
case '4':
printf("\nSending a message\nEnter message to send:");
scanf("%s", msg);
sendMessage(msg_queues[id-1], msg);
break;
case '5':
printf("\nReceiving a message\n");
printf("Message received: %s\n", receiveMessage(msg_queues[id-1]));
break;
}
}
// ...
}
msg_queues
大小为 的数组在哪里NUM_QUEUES
。
在我的解决方案中,我们希望用户输入他希望发送/接收消息的队列的标识符。我假设每个队列的标识符对应于它在数组中的索引+1,即标识符是1,...,NUM_QUEUES。
推荐阅读
- c# - 转换输出并拆分成更小的字符串
- nginx - 在本地开发中使 Nginx 帮助重定向
- java - 在 log4j 中包含 org.springframework 日志
- javascript - 如何完全匹配 Node JS Regex 中的所有情况?
- java - Java 8+ 时间戳问题与 OffsetDateTime
- javascript - 将字符串中的单词大写 - 考虑括号等
- python - 避免除以零
- python - 使用 dbf.Table:如何创建具有两个或多个字段的索引?
- postgresql - PostgreSQL get_records SQL 伪 API 函数
- php - 基于其他约束的 Syfmony 自定义验证器