linux进程间通信消息队列:msgsnd: Invalid argument
今天写了个消息队列的小测试程序结果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\n", 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] == '\0' || buffer[0] == '\n') 49 continue; 50 buffer[strlen(buffer) - 1] = '\0';//去回车符 51 st_msg_buf.msg_type = 1; //设置消息类型 52 strcpy(st_msg_buf.msg_text, buffer);//复制消息 53 54 printf("message have send to\n"); 55 if(msgsnd(msgid, (void *)&st_msg_buf, MAX_TEXT, 0) < 0){ 56 perror("msgsnd"); 57 exit(1); 58 } 59 60 if(strncmp(buffer, "end", 3) == 0)//判断是否为退出结束消息 61 running = 0; 62 63 } 64 65 return 0; 66 }
接收端源代码:
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 struct my_msg_st{ //临时消息结构 14 15 int msg_type; 16 char msg_text[MAX_TEXT]; //自定义存储空间大小 17 }; 18 19 int main() 20 { 21 key_t key; 22 int running = 1, size = 0; 23 struct my_msg_st st_msg_buf; 24 int msgid; 25 int msg_to_receiver = 0; 26 memset(&st_msg_buf, 0, sizeof(st_msg_buf)); 27 28 //创建键值 29 if((key = ftok("./", 100)) == -1){ 30 perror("ftok"); 31 exit(1); 32 } 33 printf("key : %#x\n", key); 34 35 //创建信息队列 36 if((msgid = msgget(key, 0666 | IPC_CREAT)) == -1){ 37 perror("msgget"); 38 exit(1); 39 } 40 41 42 //接受消息 43 while(running) 44 { 45 if((size = msgrcv(msgid, (void *)&st_msg_buf, 46 MAX_TEXT, msg_to_receiver,0)) < 0){ 47 perror("msgsnd"); 48 exit(1); 49 } 50 51 printf("receiver mssage: %d, %s\n", size, st_msg_buf.msg_text); 52 53 if(strncmp(st_msg_buf.msg_text, "end", 3) == 0) 54 running = 0; 55 } 56 57 if(msgctl(msgid, IPC_RMID, 0) < 0){ 58 perror("msgctl"); 59 exit(1); 60 } 61 62 return 0; 63 }