查閱資料,發現c也有消息隊列函數,令我很興奮,找了一個c的列子,c本身消息隊列收發成功了。然后我嘗試php和c對發,因為c發送的的是c的結構體
struct,所以我尋求php生成c結構體struct的辦法,我用了pack,搜索了pack,或者php
struct,出來的文章都是同一篇,完全不正確的,經過記錄c發送的數據,然后將我用php
pack的數據做對比,發現數據是一模一樣的,但是,發送給c,c無法解析。還好我有點兒php擴展基礎,找到php的消息函數,一看:我失望了,php
的消息函數發送的struct是固定的,一個int和一個char[1],經過一番測試之后,能將一個數字和一個字符串發送給c了
PHP代碼:
1
2 <?php
3 $id = msg_get_queue ( 1 );
4 if (!msg_send ($id, 317, "sdsadsdsds", false, true, $msg_err))
5 {
6
7 echo "faile!";
8 return "Msg not sent because $msg_err\n";
9 }else{
10 echo "success!";
11 }
12
13 ?>
C代碼:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <fcntl.h>
4 #include <string.h>
5 #include <unistd.h>
6 #include <sys/types.h>
7 #include <sys/ipc.h>
8 #include <sys/msg.h>
9 #define MAX_TEXT 512
10 #define BUFSIZE BUFSIZ
11
12 struct msg_st {
13 long mtype;
14 char mtext[1];
15 };
16
17 void logst(struct msg_st some_data);
18
19 int main(int argc,char **argv)
20 {
21 while(1){
22
23 int msgid1;
24 struct msg_st some_data1;
25 int msg_to_recevie = 0;
26 if((msgid1= msgget((key_t)1,0666|IPC_CREAT)) == -1)
27 {
28 perror("msgget");
29 exit(EXIT_FAILURE);
30 }
31 if(msgrcv(msgid1,(void *) &some_data1, BUFSIZ, msg_to_recevie , 0) == -1)
32 {
33 perror("msgrcv");
34 exit(EXIT_FAILURE);
35 }
36 printf("recevier mssage : %s, type= %d;\n", some_data1.mtext, some_data1.mtype);
37 //printf("%s, %d\n", msg_text, strlen(msg_text));
38
39 if(msgctl(msgid1,IPC_RMID,0) == -1)
40 {
41 fprintf(stderr,"msgctl(IPC_RMID) failed \n");
42 exit(EXIT_FAILURE);
43 }
44 //break;
45 sleep(1);
46 }
47
48 }
參考鏈接:
http://blog.csdn.net/leinchu/article/details/8132530
http://blog.csdn.net/guoping16/article/details/6584024