c - 在消息队列linux c中发送不同类型的消息
问题描述
我有这样的代码:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAXLINE 1024
struct my_msgbuf {
long mtype;
char mtext[MAXLINE];
};
int main(void)
{
struct my_msgbuf buf;
int msqid;
key_t key;
if ((key = ftok("client.c", 'B')) == -1) {
perror("ftok");
exit(1);
}
if ((msqid = msgget(key, 0644 | IPC_CREAT)) == -1) {
perror("msgget");
exit(1);
}
printf("Write a text:\n");
buf.mtype = 1;
while( fgets(buf.mtext, MAXLINE, stdin) != NULL ) {
if (msgsnd(msqid, (struct msgbuf *)&buf, sizeof(buf), 0) == -1)
perror("msgsnd");
}
if (msgctl(msqid, IPC_RMID, NULL) == -1) {
perror("msgctl");
exit(1);
}
return 0;
}
此代码使用 linux (c) 中的 ipc 消息队列发送消息,但它发送的消息类型等于“1”。我必须发送消息,但每条消息都必须具有不同的类型。我删除了“while”,只留下 fgets。没有“while”的 fget 将一直工作到新行或到达 MAXLINE。它不起作用。我想达到这样的效果:
写一个类型:
1(我)
写一个文本:
第一条消息(我)
写一个类型:
2(我)
写一个文本:
第二条消息(我)
....
编译并运行程序后,我到达:
写一个类型:
1(我)
写一个文本:
写一个类型:
2(我)
写一个文本:
写一个类型:
....
这是我修改后的代码。它出什么问题了?
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAXLINE 1024
struct my_msgbuf {
long mtype;
char mtext[MAXLINE];
};
int main(void)
{
struct my_msgbuf buf;
int msqid;
key_t key;
if ((key = ftok("client.c", 'B')) == -1) {
perror("ftok");
exit(1);
}
if ((msqid = msgget(key, 0644 | IPC_CREAT)) == -1) {
perror("msgget");
exit(1);
}
while(1){
printf("Write a type:\n");
scanf("%ld", &buf.mtype);
printf("Write a text:\n");
fgets(buf.mtext, MAXLINE, stdin);
if (msgsnd(msqid, (struct msgbuf *)&buf, sizeof(buf), 0) == -1){
perror("msgsnd");
}
}
if (msgctl(msqid, IPC_RMID, NULL) == -1) {
perror("msgctl");
exit(1);
}
return 0;
}```
解决方案
推荐阅读
- javascript - 如何让 textarea 的光标在拖放时移动到突出显示的文本的末尾?
- android - 我应该总是对所有事情都使用 ConstraintLayout 吗?
- dns - 如何使用 dig 进行相对路径 DNS 查询?
- android - 我听说“理想情况下,每个视图都应该在活动中定义”,是真的吗?
- uwp - ItemsRepeater 在使用转换器时抛出 System.InvalidCastException
- deep-learning - 为什么损失会用 swa 方法跳到 nan?
- c# - 当我查看它们时,数百个错误都消失了?
- python - 将 pandas 数据框列中的列表中的 dict 分离到不同的数据框列中
- javascript - 如何重构代码以避免全局范围?
- python-3.x - TypeError:'str' 对象不可调用 uuid 值-Python 3