今天写了个消息队列的小测试程序结果send端程序总是出现:msgsnd: Invalid argument,搞了半个小时也没搞明白,后来查资料发现我将(st_msg_buf.msg_type = 0; //设置消息类型)设置为0了,原来0表示是任意类型的消息,只有recv端才可以设置为0表示:可以接受任意类型消息。
代码:
发送端源代码:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <unistd.h> 4 #include <string.h> 5 6 #include <sys/types.h> 7 #include <sys/msg.h> 8 #include <sys/ipc.h> 9 10 #define MAX_TEXT 512 11 #define BUF_SIZE 512 12 13 14 struct my_msg_st{ //临时消息结构 15 16 int msg_type; 17 char msg_text[MAX_TEXT]; //自定义存储空间大小 18 }; 19 20 int main() 21 { 22 key_t key; 23 int running = 1; 24 struct my_msg_st st_msg_buf; 25 int msgid; 26 char buffer[BUF_SIZE]; 27 memset(&st_msg_buf, 0, sizeof(st_msg_buf)); 28 memset(buffer, 0, sizeof(buffer)); 29 30 //创建键值 31 if((key = ftok("./", 100)) == -1){ 32 perror("ftok"); 33 exit(1); 34 } 35 printf("key : %#x ", key); 36 37 //创建信息队列 38 if((msgid = msgget(key, 0666 | IPC_CREAT)) == -1){ 39 perror("msgget"); 40 exit(1); 41 } 42 printf("Enter the messge to send:"); 43 44 //发送消息 45 while(running) 46 { 47 fgets(buffer, BUF_SIZE, stdin);//读取输入的消息 48 if(buffer[0] == '