c - Message receive program only printing every other message -
i have implemented 2 programs section 7.6 of http://beej.us/guide/bgipc/output/html/multipage/mq.html.
i have extended there 2 receiving programs , 1 goes determined message type.
the problem arises in receiving program, b , c. supposed print out messages entered program everytime, print messages every other time.
this message sent, reads first 6 chars , if urgent sets the message type.
buf.mtype = 2; while(fgets(buf.mtext, sizeof buf.mtext, stdin) != null) { int len = strlen(buf.mtext); strncpy(typetest, buf.mtext, 6); if(strncmp(typetest, "urgent", 6) == 0){ buf.mtype = 1; } printf("this message %s \n", buf.mtext); /* ditch newline @ end, if exists */ if (buf.mtext[len-1] == '\n') buf.mtext[len-1] = '\0'; if (msgsnd(msqid, &buf, len+1, 0) == -1) /* +1 '\0' */ perror("msgsnd"); }
this message received, if statement checks type print out.
for(;;) { /* spock never quits! */ if (msgrcv(msqid, &buf, sizeof buf.mtext, 0, 0) == -1) { perror("msgrcv"); exit(1); } if(buf.mtype == 2){ printf("spock: \"%s\"\n", buf.mtext); } }
can shed light on why prints out every other message?
thanks.
in program must set buf.mtype
2 if input not "urgent..." must in loop, every time.
while(fgets(buf.mtext, sizeof buf.mtext, stdin) != null) { int len = strlen(buf.mtext); strncpy(typetest, buf.mtext, 6); if(strncmp(typetest, "urgent", 6) == 0){ buf.mtype = 1; } else buf.mtype= 2; // set default printf("this message %s \n", buf.mtext); /* ditch newline @ end, if exists */ if (buf.mtext[len-1] == '\n') buf.mtext[len-1] = '\0'; if (msgsnd(msqid, &buf, len+1, 0) == -1) /* +1 '\0' */ perror("msgsnd"); }
in programs b , c must set msgtyp
1 or 2 each program right message queue, example:
int main(argc, argv) { int msgtype; if (*argv[1]=='a') msgtype= 1; else if (*argv[1]=='b') msgtype= 2; else msgtype= 0; ... for(;;) { /* spock never quits! */ if (msgrcv(msqid, &buf, sizeof buf.mtext, msgtype, 0) == -1) { perror("msgrcv"); exit(1); } if(buf.mtype == msgtype){ printf("spock: \"%s\"\n", buf.mtext); } } return 0; }
Comments
Post a Comment