Reputation: 133
I am learning IPC programming. As a part of it I tried the below two codes to get to know about message queues....
Message queue creator or message sender
struct my_msgbuf {
long mtype;
char mtext[200];
};
int main(void)
{
struct my_msgbuf buf;
int msqid;
key_t key;
if ((key = ftok("kirk.c", 'B')) == -1) {
perror("ftok");
exit(1);
}
if ((msqid = msgget(key, 0644 | IPC_CREAT)) == -1) {
perror("msgget");
exit(1);
}
printf("Enter lines of text, ^D to quit:\n");
buf.mtype = 1; /* we don't really care in this case */
while(fgets(buf.mtext, sizeof buf.mtext, stdin) != NULL) {
int len = strlen(buf.mtext);
/* ditch newline at end, if it exists */
if (buf.mtext[len-1] == '\n') buf.mtext[len-1] = '\0';
if (msgsnd(msqid, &buf, len+1, 0) == -1) /* +1 for '\0' */
perror("msgsnd");
}
if (msgctl(msqid, IPC_RMID, NULL) == -1) {
perror("msgctl");
exit(1);
}
return 0;
}
Message receiver
struct my_msgbuf {
long mtype;
char mtext[200];
};
int main(void)
{
struct my_msgbuf buf;
int msqid;
key_t key;
if ((key = ftok("kirk.c", 'B')) == -1) { /* same key as kirk.c */
perror("ftok");
exit(1);
}
if ((msqid = msgget(key, 0644)) == -1) { /* connect to the queue */
perror("msgget");
exit(1);
}
printf("spock: ready to receive messages, captain.\n");
for(;;) { /* Spock never quits! */
if (msgrcv(msqid, &buf, sizeof(buf.mtext), 0, 0) == -1) {
perror("msgrcv");
exit(1);
}
printf("spock: \"%s\"\n", buf.mtext);
}
return 0;
}
the above codes can be found at beej's guide for message queue.
When I try to execute "spock" msgget() is throwing an error : No such file or directory. Is there anything wrong with ftok(). I changed the permission of file to the one passed to msgget() funcition. But same error. Thanks in advance. Thanks in advance.
Upvotes: 1
Views: 12880
Reputation: 11
Had also the same problem. If u want to execute message-receiver process u have to be sure that message-sender is also executing at that time. Otherwise msgqueue (if u ever run message-sender) would be destoroyed and id related with it will no longer be valid. Hence it's anything magicall about it. Pozdr.
Upvotes: 1
Reputation: 94594
ftok
requires that the file exists, as it uses the inode
information to construct the key. If you're building them in separate directories, pointing to kirk.c
using a relative path should work correctly e.g. spock/spock.c
contains the spock code, kirk/kirk.c
contains the kirk code, in spock/spock.c
you should refer to ../kirk/kirk.c
Upvotes: 5