#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <errno.h> #include <string.h> /* * */ typedef struct { long int nType; char szText[256]; }MSG; int main(int argc, char** argv) { key_t IKey1; int nMsgId; MSG msg; if((IKey1 = ftok("/etc/profile",1)) == -1) { perror("ftok"); exit(1); } if((nMsgId = msgget(IKey1,IPC_CREAT|IPC_EXCL|0666)) == -1) { if(errno != EEXIST) { perror("msgget"); exit(2); } if((nMsgId = msgget(IKey1,0)) == -1) { perror("msgget"); exit(3); } } printf("KeyID=%x\n",IKey1); printf("MsgID=%d\n",nMsgId); memset(&msg,0x00,sizeof(MSG)); msg.nType = 2; memcpy(msg.szText,"123456",6); if(msgsnd(nMsgId,(const void*)&msg,strlen(msg.szText),IPC_NOWAIT)<0) { perror("msgsnd"); } return 0; }
运行结果, 2 为两个消息,12 为长度,666为rwx
[root@64 ~]# ipcs -q ------ Message Queues -------- key msqid owner perms used-bytes messages 0x010088c2 0 root 666 12 2 [root@elm64 ~]#