发新话题
打印

一个小问题

一个小问题

以下SERVER-CLIENT小程序利用了消息队列的机制,但是为什么print出来的语句不全(SOLARIS2.6)?如果CLIENT发了多个消息,SERVER接受时需不需信号量的配合?
tests.c(SERVER)

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>

#define KEY1 1
#define KEY2 2

struct {
        long type;
        int len;
        char data[255];
} mesg;

main()
{
  int msgq1, msgq2;

  if ((msgq1 = msgget(KEY1, IPC_CREAT | 0666)) < 0) {
        fprintf(stderr, "create msgqueue error\n");
        exit(-1);
  }
  if ((msgq2 = msgget(KEY2, IPC_CREAT | 0666)) < 0) {
        fprintf(stderr, "create msgqueue error\n");
        exit(-1);
  }
  mesg.type=5;
  msgrcv(msgq1, &mesg, 255, mesg.type, 0);
  mesg.len = strlen(mesg.data);
  printf("%s, %d\n", mesg.data, mesg.len);
  strcpy(mesg.data, "hi, how are you?");
  mesg.len = strlen(mesg.data);
  msgsnd(msgq2, &mesg, mesg.len, 0);

}

testc.c(CLIENT)
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>

#define KEY1 1
#define KEY2 2

struct {
        long type;
        int len;
        char data[255];
} mesg;

main()
{
  int msgq1, msgq2;

  if ((msgq1 = msgget(KEY1, 0)) < 0) {
        fprintf(stderr, "create msgqueue error\n");
        exit(-1);
  }
  if ((msgq2 = msgget(KEY2, 0)) < 0) {
        fprintf(stderr, "create msgqueue error\n");
        exit(-1);
  }
  mesg.type=5;
  strcpy(mesg.data, "hello?");
  mesg.len = strlen(mesg.data);
  msgsnd(msgq1, &mesg, mesg.len, 0);
  msgrcv(msgq2, &mesg, 255, mesg.type, 0);
  mesg.len = strlen(mesg.data);
  printf("%s %d\n", mesg.data, mesg.len);
  msgctl(msgq1, IPC_RMID, 0);
  msgctl(msgq2, IPC_RMID, 0);
}

testc.c
      

TOP

modify

我将mesg结构改了一下,将mesg.len去掉,就OK了,这样的话,难道mesg一定就得是这样的结构了吗?      

TOP

帮帮我!

不好意思:),我还是有点不明白。我自定义了个mesg的结构,里面有len字段是为了当我的CLIENT给SERVER发了若干个不等长的消息,这样SERVER就不可以单纯地用msgrcv来收了,应该是先收下mesg的head,通过读len知道具体的DATA的长度,再读信息,可是怎样实现呢?      

TOP

发新话题