Linux-进程间的通信

  • 本文出自<svtter.github.io>

实验内容

消息的创建,发送,和接收。

<任务>

使用系统调用 msgget( ), megsnd( ), msgrev( )及 msgctl()编制一长度为 1K 的消息发送和接收的程序 。

程序设计

  1. 为了便于操作和观察结, 用一个程序为引子 , 先后fork( )两个子进程 , SERVER 和 CLIENT,进行通信。
  2. SERVER 端建立一个 Key 为 75 的消息队列,等待其他进程发来的消息。当遇到类型为 1 的消息,
则作为结束信号,取消该队列,并退出 SERVER 。SERVER 每接收到一个消息后显示一句 “(server)received”。
  1. CLIENT 端使用 Key 为 75 的消息队列,先后发送类型从 10 到 1 的消息,然后退出。最后的一个
消息,既是 SERVER 端需要的结束信号。CLIENT 每发送一条消息后显示一句“(client)sent”。
  1. 父进程在 SERVER 和 CLIENT 均退出后结束。

使用的函数

并非每次创建消息队列都会成功,所以重新添加-1情况的判断。

可以使用ipcs -q命令查看

源代码

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/wait.h>
#define MSGKEY 75
struct msgform
{
    long mtype;
    char mtexe[100];
}msg;
int msgqid, i;
void CLIENT()
{
    int i;
    msgqid = msgget(MSGKEY, 0777|IPC_CREAT);
    if( msgqid == -1)
    {
        puts("client error in build");
        return;
    }
    else
        printf("client qid is: %d\n", msgqid);
    for (i = 10; i >= 1; i --)
    {
        msg.mtype = i;
        printf("(client)sent mtype %ld.\n", msg.mtype);
        msgsnd(msgqid, &msg, strlen(msg.mtexe)+1, );
    }
    puts("client exit...");
    exit();
}
void SERVER()
{
    msgqid = msgget(MSGKEY, 0777|IPC_CREAT);
    if( msgqid == -1)
    {
        printf("error in build.\n");
        return;
    }
    else
        printf("server qid is: %d\n", msgqid);
    do
    {
        msgrcv(msgqid, &msg, 1030, , );
        printf("(server)received mtype %ld.\n", msg.mtype);
    } while (msg.mtype != 1);
    msgctl(msgqid, IPC_RMID, );
    puts("server exit...");
}
int main ()
{
    if(fork())
    {
        SERVER();
        wait();
    }
    else
        CLIENT();
    return ;
}

运行结果

进程间的通信