Linux 消息队列。

编程使用消息队列从父进程发送10个整数到子进程,子进程收下来后计算总和,后用同一个消息队列把总和发回给父进程显示。可用整数数组的方式发送,或者用循环逐个整数发送。

详细代码如下,望采纳

//父进程代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

struct msgbuf
{
    long mtype;
    int data[10];
};

int main()
{
    int msgid;
    struct msgbuf buf;
    int sum = 0;
    int i;

    //创建消息队列
    msgid = msgget(IPC_PRIVATE, 0666);
    if (msgid < 0)
    {
        printf("msgget error\n");
        return -1;
    }

    //发送消息
    buf.mtype = 1;
    for (i = 0; i < 10; i++)
    {
        buf.data[i] = i;
        sum += i;
    }
    msgsnd(msgid, &buf, sizeof(buf.data), 0);

    //接收消息
    msgrcv(msgid, &buf, sizeof(buf.data), 2, 0);
    printf("sum = %d\n", buf.data[0]);

    //删除消息队列
    msgctl(msgid, IPC_RMID, NULL);

    return 0;
}

//子进程代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

struct msgbuf
{
    long mtype;
    int data[10];
};

int main()
{
    int msgid;
    struct msgbuf buf;
    int sum = 0;
    int i;

    //获取消息队列
    msgid = msgget(IPC_PRIVATE, 0666);
    if (msgid < 0)
    {
        printf("msgget error\n");
        return -1;
    }

    //接收消息
    msgrcv(msgid, &buf, sizeof(buf.data), 1, 0);
    for (i = 0; i < 10; i++)
    {
        sum += buf.data[i];
    }

    //发送消息
    buf.mtype = 2;
    buf.data[0] = sum;
    msgsnd(msgid, &buf, sizeof(buf.data), 0);

    return 0;
}