读书人

linux上的 消息通信

发布时间: 2013-01-17 10:28:54 作者: rapoo

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>
#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("/tmp/2",'a');

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

msgid=msgget(key,IPC_CREAT|0666);

if(msgid==-1)

{

printf("create error\n");

return -1;

}




while(1){


while(1){
msgbuf.mtype = 1;

memset(&msgbuf,0,sizeof(msgbuf));

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

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

msgbuf.mtype = 2;

strcpy(msgbuf.data,"11111111");

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

if(ret==-1)

{

printf("send message err\n");

return -1;

}
}

}


linux上的 消息通信
[解决办法]
msgbuf.mtype = 1/2;
memset(&msgbuf,0,sizeof(msgbuf));
ret=msgrcv(msgid,&msgbuf,sizeof(msgbuf.data),msgbuf.mtype,IPC_NOWAIT);

这一步,lz犀利了
[解决办法]
memset(&msgbuf,0,sizeof(msgbuf));
msgbuf.mtype = 1
[解决办法]
2;
放在前面使用memset函数后无效了。

读书人网 >UNIXLINUX

热点推荐