Chcę napisać program, który uruchomię w 1 okienku konsoli, a następnie ponownie uruchomię ten sam program w innej konsoli (okno) i obie instancje tego samego programu mają komunikować się przez kolejki komunikatów. Napisałem program, ale on nie do końca działa, :/ widzę to w pierwszym oknie konsoli:
i to, w drugim okienku konsoli:
Co jest nie tak i jak to poprawić?
to mój kod:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
struct mymsgbuf{
long mtype;
int mtext;
} msg1, msg2;
int main(int argc, char **argv)
{
int msgqid1, msgqid2;
printf("Deleting queues ...\n");
int key1 = msgget(ftok("/tmp/", 1), 0);
if(key1 > 0)
{
printf("Deleting first queue ...\n");
msgctl(key1, IPC_RMID, 0);
}
int key2 = msgget(ftok("/tmp/", 2), 0);
if(key2 > 0)
{
printf("Deleting second queue ...\n");
msgctl(key2, IPC_RMID, 0);
}
msgqid1 = msgget(ftok("/tmp", 1), IPC_CREAT | IPC_EXCL | 0600);
if(msgqid1 == -1)
{
printf("Second process\n");
msgqid2 = msgget(ftok("/tmp/", 1), 0);
msgqid1 = msgget(ftok("/tmp/", 2), IPC_CREAT | 0600);
}else
{
printf("First process\n");
msgqid2 = msgget(ftok("/tmp/", 2), IPC_CREAT | 0600);
}
printf("MSGID1 = %d, MSGID2 = %d\n", msgqid1, msgqid2);
msg1.mtype = 1;
msg2.mtype = 1;
while(1)
{
printf("\n> ");
scanf("%d", &msg1.mtext);
if(msgsnd(msgqid1, &msg1, sizeof(msg1.mtext), 0) == -1)
perror("snd");
if(msgrcv(msgqid2, &msg2, sizeof(msg2.mtext), 0, 0) == -1)
perror("rcv");
printf("Send: %d\n", msg1.mtext);
printf("Received: %d\n", msg2.mtext);
}
if (msgctl(msgqid1, IPC_RMID, NULL) == -1)
{
perror("msgctl");
exit(1);
}
if (msgctl(msgqid2, IPC_RMID, NULL) == -1)
{
perror("msgctl");
exit(1);
}
return 0;
}