Is it possible, in c, that 2 different process wait to receive a different type of message in the same queue??
Example: Process 1 wait Message type 4 and Process 2 wait Message type 3 in queue key = 0x000200
Cause i have 2 process that get the id of the queue and wait to a message but only when i remove one of the msgrcv it works.
Or maybe the problem is that i used as type = 0...?
CodePudding user response:
Or maybe the problem is that i used as type = 0...?
Yes, the sender should set the message type into (e.g.) mtype
of the [given] message struct. And, the receiver should pass the desired message type as the msgtyp
argument to msgrcv
.
Here is some example code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/msg.h>
#include <sys/wait.h>
int qid;
typedef struct {
long mtype;
char mtext[1];
} mymsg_t;
// dosnd -- sender process
void
dosnd(void)
{
mymsg_t msg;
for (int idx = 0; idx <= 20; idx) {
// set message type in message!
msg.mtype = (idx & 1) 1;
printf("dosnd: sending %ld\n",msg.mtype);
msgsnd(qid,&msg,sizeof(msg.mtext),0);
}
exit(0);
}
// rcvone -- receive messages of a given type
void
rcvone(int type)
{
mymsg_t msg;
for (int idx = 0; idx < 5; idx) {
msgrcv(qid,&msg,sizeof(msg.mtext),type,0);
printf("rcvone: got %ld\n",msg.mtype);
}
}
// rcvall -- receive all [remaining] messages of any type
void
rcvall(void)
{
mymsg_t msg;
while (1) {
if (msgrcv(qid,&msg,sizeof(msg.mtext),0,IPC_NOWAIT) < 0)
break;
printf("rcvall: got %ld\n",msg.mtype);
}
}
// dorcv -- receiver process
void
dorcv(void)
{
sleep(2);
rcvone(1);
rcvone(2);
rcvall();
exit(0);
}
int
main(void)
{
// set output line buffering (if using logfile)
setlinebuf(stdout);
// get queue ID (create message queue)
qid = msgget(IPC_PRIVATE,IPC_CREAT | 0644);
pid_t pid;
// create sender process
pid = fork();
if (pid == 0)
dosnd();
// create receiver process
pid = fork();
if (pid == 0)
dorcv();
// wait for all processes to complete
while (1) {
pid = wait(NULL);
if (pid < 0)
break;
}
return 0;
}
Here is the program output:
dosnd: sending 1
dosnd: sending 2
dosnd: sending 1
dosnd: sending 2
dosnd: sending 1
dosnd: sending 2
dosnd: sending 1
dosnd: sending 2
dosnd: sending 1
dosnd: sending 2
dosnd: sending 1
dosnd: sending 2
dosnd: sending 1
dosnd: sending 2
dosnd: sending 1
dosnd: sending 2
dosnd: sending 1
dosnd: sending 2
dosnd: sending 1
dosnd: sending 2
dosnd: sending 1
rcvone: got 1
rcvone: got 1
rcvone: got 1
rcvone: got 1
rcvone: got 1
rcvone: got 2
rcvone: got 2
rcvone: got 2
rcvone: got 2
rcvone: got 2
rcvall: got 1
rcvall: got 2
rcvall: got 1
rcvall: got 2
rcvall: got 1
rcvall: got 2
rcvall: got 1
rcvall: got 2
rcvall: got 1
rcvall: got 2
rcvall: got 1