Linux 进程间通讯详解四

msgsnd函数
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
--功能:把一条消息添加到消息队列中
--参数 
    msqid:由msgget函数返回的消息队列标识码
    msgp:是一个指针,指针指向准备发送的消息
    msgsz:是msgp指向的消息的长度,这个长度不含保存消息类型的那个long int长整型
    msgflg:控制着当前消息队列满或到达系统上限时将要发生的事情
--成功返回0,失败返回-1并且设置errno
--msgflg=IPC_NOWAIT表示队列满不等待,返回EAGAIN错误
--消息结构在两方面受到制约。首先,它必须小于系统规定的上限值;其次,它必须以一个long int长整数开始,接收者函数将利用这个长整数确定消息的类型
struct msgbuf {
               long mtype;       /* message type, must be > 0 */
               char mtext[1];    /* message data */
           };
//消息队列--msgsnd
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

//发送消息的结构体
struct msgbuf
{
    long mtype; /* message type, must be > 0 */
    char mtext[1024]; /*这是占位符,由程序员自己决定发送消息的数组长度 */
};

int main(int arg, char * args[])
{
    int msqid = msgget(0x1234, 0666 | IPC_CREAT);
    if (msqid == -1)
    {
        perror("msgget() err");
        return -1;
    }
    printf("创建消息队列成功!msqid=%d
", msqid);
    //发送消息
    struct msgbuf buf;
    memset(&buf,0,sizeof(buf));
    buf.mtype=1;
    strcpy(buf.mtext,"这是我发送的消息体-aaaaaaabbbbaaaaaaaa1111111aa!
");
    int ret=msgsnd(msqid,&buf,20,IPC_NOWAIT);
    if(ret==-1)
    {
        perror("msgsnd() err");
        return -1;
    }
    printf("消息发送成功!
");
    return 0;
}
原文地址:https://www.cnblogs.com/zhanggaofeng/p/6200871.html