//rec.c
#include<stdlib.h> #include<stdio.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/msg.h> typedef struct { long msgtype; char msgdata[512]; }msgbuf; int main() { msgbuf msgRec; int iRet = -1; int iMsgID = -1; //create msgque iMsgID = msgget((key_t)1111,0660|IPC_CREAT); if(iMsgID == -1){ printf("error 1!"); return -1; } while(1){ memset(msgRec.msgdata,0x00,sizeof(msgRec.msgdata)); //rec data param 3 means iRet =msgrcv(iMsgID,(void*)&msgRec,512,1,0); if(iRet == -1){ printf("error 2!"); return -2; } printf("You wrote: %s len is [%d] ",msgRec.msgdata,strlen(msgRec.msgdata)); } return 1; if(msgctl(iMsgID, IPC_RMID, 0) == -1) { printf("error 3!"); return -3; } }
snd.c
input data: cd^H^H^C root@ubuntu:/usr/src/ipc# ls #include<stdlib.h> #include<stdio.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/msg.h> typedef struct { long msgtype; char msgdata[512]; } msgbuf; int main() { msgbuf Sendmsg; char sBuf[512]; int iMsgID = -1; int iRet = -1; //create msgque iMsgID = msgget((key_t)1111,0660|IPC_CREAT); if(iMsgID == -1){ printf("error 111!"); return -1; } while(1){ printf("input data: "); memset(sBuf,0x00,sizeof(sBuf)); fgets(sBuf,512,stdin); Sendmsg.msgtype = 1; // memcpy(Sendmsg.msgdata,sBuf,strlen(sBuf)); strcpy(Sendmsg.msgdata,sBuf); //send iRet =msgsnd(iMsgID,(void*)&Sendmsg,strlen(Sendmsg.msgdata),0); printf("send data = [%s] len = [%d] ",Sendmsg.msgdata,strlen(Sendmsg.msgdata)); if(iRet == -1){ printf("error 2"); return -2; } } return 1; }
缺少自信的人啊,要快快快快成长!!!