Linux下C語言編程(二)消息隊列的發送和接收

Linux下C語言編程(二)消息隊列的發送和接收


發送消息隊列

/*send.c*/  
#include <stdio.h>   
#include <sys/types.h>   
#include <sys/ipc.h>   
#include <sys/msg.h>   
#include <errno.h>   

#define MSGKEY 1024   

struct msgstru  
{  
   long msgtype;  
   char msgtext[2048];   
};  

main()  
{  
  struct msgstru msgs;  
  int msg_type;  
  char str[256];  
  int ret_value;  
  int msqid;  

  msqid=msgget(MSGKEY,IPC_EXCL);  /*檢查消息隊列是否存在*/  
  if(msqid < 0){  
    msqid = msgget(MSGKEY,IPC_CREAT|0666);/*創建消息隊列*/  
    if(msqid <0){  
    printf("failed to create msq | errno=%d [%s]\n",errno,strerror(errno));  
    exit(-1);  
    }  
  }   

  while (1){  
    printf("input message type(end:0):");  
    scanf("%d",&msg_type);  
    if (msg_type == 0)  
       break;  
    printf("input message to be sent:");  
    scanf ("%s",str);  
    msgs.msgtype = msg_type;  
    strcpy(msgs.msgtext, str);  
    /* 發送消息隊列 */  
    ret_value = msgsnd(msqid,&msgs,sizeof(struct msgstru),IPC_NOWAIT);  
    if ( ret_value < 0 ) {  
       printf("msgsnd() write msg failed,errno=%d[%s]\n",errno,strerror(errno));  
       exit(-1);  
    }  
  }  
  msgctl(msqid,IPC_RMID,0); //刪除消息隊列   
}

這裏寫圖片描述

接收消息隊列

/*receive.c */  
#include <stdio.h>   
#include <sys/types.h>   
#include <sys/ipc.h>   
#include <sys/msg.h>   
#include <errno.h>   

#define MSGKEY 1024   

struct msgstru  
{  
   long msgtype;  
   char msgtext[2048];  
};  

/*子進程,監聽消息隊列*/  
void childproc(){  
  struct msgstru msgs;  
  int msgid,ret_value;  
  char str[512];  

  while(1){  
     msgid = msgget(MSGKEY,IPC_EXCL );/*檢查消息隊列是否存在 */  
     if(msgid < 0){  
        printf("msq not existed! errno=%d [%s]\n",errno,strerror(errno));  
        sleep(2);  
        continue;  
     }  
     /*接收消息隊列*/  
     ret_value = msgrcv(msgid,&msgs,sizeof(struct msgstru),0,0);  
     printf("text=[%s] pid=[%d]\n",msgs.msgtext,getpid());  
  }  
  return;  
}  

void main()  
{  
  int i,cpid;  

  /* create 5 child process */  
  for (i=0;i<5;i++){  
     cpid = fork();  
     if (cpid < 0)  
        printf("fork failed\n");  
     else if (cpid ==0) /*child process*/  
        childproc();  
  }  
}

這裏寫圖片描述
左側是發送端:input message type(end:0):數字判斷是否結束,輸入0結束,輸入其他下一步輸入要發送的string;
右側是接收端(監聽):其中text表示監聽到的內容,pid表示是哪個線程監聽到這條消息隊列;


ps:

1.c語言中scanf

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章