kin*_*er1 2 c linux message-queue
任何人都可以帮我指出我的程序中的错误是什么?
在此先感谢,kingsmasher1
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <errno.h>
typedef struct msgbuf {
long mtype; /* message type, must be > 0 */
char mtext[15]; /* message data */
} msgbuf;
int main() {
key_t key;
int msqid, pid, length;
msgbuf buf;
msqid=msgget(IPC_PRIVATE,IPC_CREAT);
if(msqid==-1){
perror("msgget failed");
return;
}
else {
printf("msgget succeeded. ID:%u",msqid);
}
pid=fork();
if(pid==-1) {
perror("fork failed\n");
}
buf.mtype=1;
strcpy(buf.mtext, "This is a test message");
length=sizeof(buf.mtext);
if(msgsnd(msqid,&buf,length,0)!=0) {
perror("msgsnd failed:\n");
}
else {
printf("msgsnd succeeded\n");
}
}
Run Code Online (Sandbox Code Playgroud)
输出:msgsnd失败:参数无效
您的buf.mtext(15个字符)中没有足够的空间("This is a test message"对于NUL终结符,一个或多个23个字符).
我说有可能破坏你的类型的好机会,甚至一些其他堆栈上的一条信息(如msqid或length或key).
无论这是否是实际问题,它仍然是未定义的行为,应该修复.我要做的第一件事是检查替换:
strcpy(buf.mtext, "This is a test message");
Run Code Online (Sandbox Code Playgroud)
有:
strcpy(buf.mtext, "XYZZY"); // 5 plus the NUL
Run Code Online (Sandbox Code Playgroud)
看它是否修复它.
或者,mtext大到足以存储您放在那里的数据.
| 归档时间: |
|
| 查看次数: |
10710 次 |
| 最近记录: |