msgid创建报错:求助msgget创建消息队列ID的解决方案
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
progfileexists first—you can create it withtouch progfilein 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
0666permission 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 -qto list existing queues, andsysctl kernel.msgmnito 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
- Create the
progfileif it doesn't exist: runtouch progfilein your terminal. - Compile with warnings enabled to catch issues early:
gcc your_file.c -o msg_queue -Wall. - 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). - 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

