进程的通信—消息的发送与接收

在父进程中创建一个消息队列,fork 创建一个子进程,在子进程中将一条消息传送至消息队列,父进程接受队列的消息,并将消息送屏幕显示。

#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/msg.h>
#include<sys/ipc.h>
#include<string.h>
#define MSGKEY 75
typedef struct msgform
{
        int mtype;
        char mtext[1000];
}msg;
int msgqid;
int main()
{
        msg msg1,msg2;
        int sp;
        int sndid,rcvid;
        while((sp=fork())==-1);
        if(sp==0)
        {
                msgqid=msgget(MSGKEY,0777);
                strcpy(msg1.mtext,"message\0");
                sndid=msgsnd(msgqid,&msg1,1024,0);
                if(sndid==0)
                        printf("success to send!\n");
                else
                        printf("fail to send!\n");    
                exit(0);
        }
        else
        {
                wait(NULL);
                msgqid=msgget(MSGKEY,0777|IPC_CREAT);
                rcvid=msgrcv(msgqid,&msg2,1030,0,0);
                if(rcvid==1024)
                        printf("succeed to recieve \"%s\"\n",msg2.mtext);
                else
                        printf("fail to receive!\n");
                msgctl(msgqid,IPC_RMID,0);
                exit(0);
        }
        return 0;        
}

 

代码分析:

代码过程就是题目中所要求的,要注意的是:msgrcv()的返回值是所传送消息的长度。

 

 

posted @ 2017-11-03 21:25  奇热行  阅读(724)  评论(0)    收藏  举报