【问题标题】:Msgrcv does not receive messages however they have been sent properlyMsgrcv 没有收到消息,但它们已正确发送
【发布时间】:2018-12-20 10:43:46
【问题描述】:

我正在编写一个基本的服务器程序,它必须从客户端接收两种类型的消息(第一个消息是类型 1,第二个是类型 2)。似乎它没有看到来自已正确发送的客户端的消息(msgsnd 不返回-1)。我读到它可能是由太大的消息引起的,但我的消息就像几个字符长,我的缓冲区是 100。我没有发现我创建的结构有任何差异,msgget 也没有返回任何错误。这是服务器程序代码:

struct msgbuf
{
  long type;
  char text[100];
}m1;

int main()
{
  int id;
  if (id = msgget(1998,0666|IPC_EXCL)==-1) {
     printf("msgget error");
  }
  char first_msg[100][100];
  char second_msg[100][100];
  int counter = 0;
  while (counter < 100) {
     msgrcv(id,&m1,sizeof(m1.text),1,0);
     printf("%s",m1.text);
     strcpy(first_msg[counter], m1.text);
     msgrcv(id,&m1,sizeof(m1.text),2,0);
     printf("%s",m1.text);
     strcpy(second_msg[counter],m1.text);
     counter++;
  }
  return 0;
}

还有一个客户端代码:

struct msgbuf
{
   long type;
   char text[100];
};

int main()
{
   struct msgbuf m1,m2;
   int id;
   if ((id = msgget(1998,0666|IPC_EXCL)) == -1) {
     printf("error");
   }
   char first_msg[90];
   scanf("%s",&first_msg[0]);
   char second_msg[90];
   scanf("%s",&second_msg[0]);
   m1.type = 1;
   strcpy(m1.text,first_msg);
   if (msgsnd(id,&m1,sizeof(m1.text),0) == -1) {
     perror("msgsnd failed");
  }
  m2.type = 2;
  strcpy(m2.text,second_msg);
  if (msgsnd(id,&m2,sizeof(m2.text),0)==-1) {
    perror("msgsnd2 failed");
  }
  return 0;
}

【问题讨论】:

  • 你听说过identation吗?
  • 抱歉,我觉得现在更好看
  • if (id = msgget(1998,0666|IPC_EXCL)==-1) { ...another 示例说明为什么将赋值放在条件中是非常糟糕的代码。 id = msgget(1998,0666|IPC_EXCL); if ( id == -1 ).... 会完全避免这个错误。将作业塞入条件中是个坏主意,不会给您带来任何好处。

标签: c ipc msgrcv


【解决方案1】:

这是一个由运算符优先级问题引起的讨厌的错误。

在客户端,你写得正确:

if ((id = msgget(1998,0666|IPC_EXCL)) == -1) {

parens 确保您首先分配给 id,然后与 -1 进行比较。

但在服务器中,你只有:

if (id = msgget(1998,0666|IPC_EXCL)==-1) {

不幸的是它实际上是if (id = (msgget(1998,0666|IPC_EXCL)==-1)),因为比较的优先级高于赋值!

修复很简单:只需在 server.c 中添加括号,就像在 client.c 中一样

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多