-1

I sent message from one process to another using message queue. The process receiving messages prints output only after all calls to msgrcv function are done. What I was expecting is that it will print data as it receives a message but it prints data only after receiving all messages.

I have tried changing permissions. Ihave used 0666 | IPC_NOWAIT, 0666 | IPC_NOWAIT | IPC_CREAT.

server.c

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
#include <string.h>

struct mesg_buffer {
  long mtype;
  char mtext[100];
};

int main(void){
  struct mesg_buffer message;
  int sq_msgid, uq_msgid;
  int num_users = 0;
  sq_msgid = msgget(ftok("server_queue",1), 0666 | IPC_CREAT);
  uq_msgid = msgget(ftok("user_queue",1), 0666 | IPC_CREAT);
  for(int i=0;i<2;i++){
    printf("%ld",msgrcv(sq_msgid, &message, sizeof(message), 1, 0));
  }
}

client.c

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <pthread.h> 
#include <semaphore.h>
#include <signal.h>
#include <string.h>

struct mesg_buffer {
  long mtype;
  char mtext[100];
};

int main(void){
  struct mesg_buffer message;
  int sq_msgid, uq_msgid;
  sq_msgid = msgget(ftok("server_queue",1), 0666 | IPC_CREAT);
  strcpy(message.mtext, "join");
  message.mtype = 1;
  int r = msgsnd(sq_msgid, &message, sizeof(message), 0);
  printf("%d", r);
}
s.singh
  • 62
  • 11
  • 1
    Try adding newlines to your `printf()` calls or use `fflush(stdout)` after them. – Shawn Jul 29 '19 at 08:04
  • Figured it would. Nothing to do with `msgrcv()`, everything to do with stdio buffering. – Shawn Jul 29 '19 at 08:24
  • why do we need to flush output here? – s.singh Jul 29 '19 at 09:38
  • https://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin Also, you're not checking the return value from `ftok()`. Using `ftok()` to get a message queue ID is pretty error-prone. The file must exist, there's no guarantee that if the file is deleted and recreated you wind up with the same number, and there's no guarantee that even if `ftok()` works that you'll get a value back that uniquely identifies a message queue with - `ftok()` can return a value that will refer to a queue that's already in use by someone/something else. – Andrew Henle Jul 29 '19 at 09:54
  • 1
    @s.singh you need to flush (or use '\n' in print) because printf (and other functions of stdio) make some kind of optimization by waiting one of those 2 triggers before displaying anything. It then reduces the amount of calls to write () which hides a syscall and fastens your program ;) – Angevil Jul 29 '19 at 10:02

1 Answers1

0

As I get response in comments, whenever I need to show output to console, I just need to use fflush(stdout).

s.singh
  • 62
  • 11