IP phone日志2

类别:软件工程 点击:0 评论:0 推荐:

昨天把socket学习了一下:
今天开始学习queue.
以下是queue.c代码
**********************************************************
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>

#define MSG_MAX 4056 // <= 4056  max size of message (bytes)


/* message buffer for msgsnd and msgrcv calls */ //定义的信息
struct sMsgBuf {
  long mtype; // type of message
  long ModuleID;//module ID
  char mtext[MSG_MAX]; //message text */
};

//创建queue
int open_queue( key_t keyval )
{
  int qid;
  if((qid = msgget( keyval, IPC_CREAT | 0660 )) == -1)
    {
      return(-1);
    }
  return(qid);
}


//send queue message
//qid = queue id
//qbuf = send message buffer
int send_message( int qid, struct sMsgBuf *qbuf )
{
  int result, length;
  /* The length is essentially the size of the structure minus sizeof(mtype) */
  length = sizeof(struct sMsgBuf) - sizeof(long);
  if((result = msgsnd( qid, qbuf, length, 0)) == -1)
    {
      return(-1);
    }
  return(result);
}

//read queue message
//qid = queue id
//type = message type
//qbuf = read message buffer
//return int = err code
int read_message( int qid, long type, struct sMsgBuf *qbuf )
{
  int result, length;
  /* The length is essentially the size of the structure minus sizeof(mtype) */
  length = sizeof(struct sMsgBuf) - sizeof(long);
  if((result = msgrcv( qid, qbuf, length, type, 0)) == -1)
    {
      return(-1);
    }
  return(result);
}

//查看队列是否有消息
int peek_message( int qid, long type )
{
  int result, length;

//忽略了缓冲区的地址和长度。这样,系统调用将会失败。尽管如此,
//可以检查返回的E 2 B I G值,它说明符合条件的消息确实存在。
  if((result = msgrcv( qid, NULL, 0, type, IPC_NOWAIT)) == -1)
    {
      if(errno == E2BIG)
        return 1;
    }
  return 0;
}

//sample queue
int CreateQue()
{
  int qid;
  key_t msgkey;

  struct sMsgBuf msgbuf;
  /* Generate our IPC key value */
  msgkey = ftok(".", 'm');
  /* Open/create the queue */
  if(( qid = open_queue( msgkey)) == -1) {
    perror("open_queue");
    exit(1);
  }
 msgbuf.mtype = 1;
  msgbuf.ModuleID=100;
  strcpy(msgbuf.mtext,"love");
  if((send_message( qid, &msgbuf )) == -1) {
    perror("send_message");
    exit(1);
  }
}

int get_queue_ds( int qid, struct msqid_ds *qbuf )
{
  if( msgctl( qid, IPC_STAT, qbuf) == -1)
    {
      return(-1);
    }
  return(0);
}
int change_queue_mode( int qid, char *mode )
{
  struct msqid_ds tmpbuf;
  /* Retrieve a current copy of the internal data structure */
  get_queue_ds( qid, &tmpbuf);
  /* Change the permissions using an old trick */
  sscanf(mode, "%ho", &tmpbuf.msg_perm.mode);
  /* Update the internal data structure */
  if( msgctl( qid, IPC_SET, &tmpbuf) == -1)
    {
      return(-1);
    }
  return(0);
}

int Remove_queue(int qid )
{
  if( msgctl( qid, IPC_RMID, 0) == -1)
  {
      return(-1);
  }
  return(0);
  //(void)msgctl(qid,IPC_RMID,0);
}


**********************************************************

本文地址:http://com.8s8s.com/it/it34354.htm