日期:2014-05-16  浏览次数:20633 次

linux下的 消息通信
本帖最后由 kaly_liu 于 2013-01-04 16:16:11 编辑
目标:实现A和B程序的 间隔打印出收到的消息 0000 1111 0000 1111 0000 1111......
但是我在pc的linux下运行后没有输出,就是卡在那里了,我先运行A的,然后开启另一个终端,运行B。
都是在root模式下运行的。
A.C

#include <sys/types.h>

#include <sys/msg.h>

#include <unistd.h>
#include <stdio.h> 
#include <stdlib.h> 
#include <errno.h> 
#include <string.h> 
#include <netdb.h> 

#define key 0x000000FF

struct msg_buf

    {

        int mtype;

        char data[255];

    };

 

int main()

{

     //   key_t key;

        int msgid;

        int ret;

        struct msg_buf msgbuf;

 

       // key=ftok("./2","w+");

        printf("key =[%x]\n",key);

        msgid=msgget(key,IPC_CREAT|0666);



        if(msgid==-1)

        {

                printf("create error\n");

                return -1;

        }

 

        msgbuf.mtype = 1;



while(1){



msgbuf.mtype = 1;
        strcpy(msgbuf.data,"0000");

        ret=msgsnd(msgid,&msgbuf,sizeof(msgbuf.data),IPC_NOWAIT);

        if(ret==-1)

        {

                printf("send message err\n");

                return -1;

        }
    while(1){
msgbuf.mtype = 2;
        memset(&msgbuf,0,sizeof(msgbuf));

        ret=msgrcv(msgid,&msgbuf,sizeof(msgbuf.data),msgbuf.mtype,IPC_NOWAIT);

if(msgbuf.data[1] == '1')
{
printf("recv msg =[%s]\n",msgbuf.data);
break;
}
          
    sleep(1);
     }

  } 

}


B.C

#include <sys/types.h>

#include <sys/msg.h>

#include <unistd.h>
#include <stdio.h> 
#include <stdlib.h> 
#include <errno.h> 
#include <string.h>&nb