You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

msgid创建报错:求助msgget创建消息队列ID的解决方案

Troubleshooting msgget() Returning -1 in Your Message Queue Setup

Hey there, let's break down why your msgget() call is failing and fix it step by step!

Common Causes & Fixes

1. Hardcoded Key Conflicts

You're using a hardcoded key_t value (1234), which might already be in use by another IPC resource on your system. Hardcoded keys are unreliable for unique resource identification—this is a super common pitfall.

Fix: Use ftok() to generate a unique, system-wide key instead. You had this commented out in your code, so let's uncomment and use it properly:

  • ftok() takes an existing file path (like your program's source file) and a project ID (a non-zero byte) to generate a unique key.
  • Make sure the file progfile exists first—you can create it with touch progfile in your terminal if it doesn't.

2. Missing Error Context

Your code only prints "[-]Error..." but doesn't tell you why it failed. Without specific error details (like permission denied, resource limit reached, etc.), debugging is just guesswork.

Fix: Include <errno.h> and <string.h> to use perror() or strerror(errno) and get detailed error messages.

3. Permission or System Limits

  • The 0666 permission mode is correct, but double-check that your user has the necessary privileges to create IPC resources.
  • Your system might have hit the maximum number of allowed message queues. Run ipcs -q to list existing queues, and sysctl kernel.msgmni to view the current limit.

Corrected Code

Here's your updated code with all fixes applied:

#include<stdio.h>
#include<stdlib.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<errno.h>
#include<string.h>

struct msg_buf{
 long msg_type;
 char msg_txt[100];
}message;

int main() {
 int msgid;
 key_t key;

 // Generate a unique key using ftok
 key = ftok("progfile", 65);
 if (key == -1) {
     perror("ftok failed");
     exit(EXIT_FAILURE);
 }

 // Create or access the message queue
 msgid = msgget(key, 0666 | IPC_CREAT);
 if (msgid == -1) {
     printf("[-]Error... ");
     perror("msgget failed");
     exit(EXIT_FAILURE);
 }

 printf("[+]Message queue created successfully with ID: %d\n", msgid);
 return 0;
}

Additional Steps

  1. Create the progfile if it doesn't exist: run touch progfile in your terminal.
  2. Compile with warnings enabled to catch issues early: gcc your_file.c -o msg_queue -Wall.
  3. If you still get a permission error, try running the program with sudo (only as a last resort—verify your user's IPC permissions first).
  4. If resource limits are the issue, adjust the kernel parameter with sudo sysctl -w kernel.msgmni=128 (or a higher value) if needed.

内容的提问来源于stack exchange,提问作者Brahma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:37:15