views:

238

answers:

2

I open a mesage queue in a .c file, and upon success it says the message queue id is 3. While that program is still running, in another terminal I start another program (of another .c file), that creates a new message queue with a different mqd_t. But its id also appears as 3. Is this a problem?

server file goes like this:

void server(char* req_mq) {
struct mq_attr attr;
mqd_t mqdes;
struct request* msgptr;

int n;
char *bufptr;
int buflen;
pid_t apid;

//attr.mq_maxmsg = 300;
//attr.mq_msgsize = 1024;

mqdes = mq_open(req_mq, O_RDWR | O_CREAT, 0666, NULL);
if (mqdes == -1) {
    perror("can not create msg queue\n");
    exit(1);
}
printf("server mq created, mq id = %d\n", (int) mqdes);

and the client goes like:

void client(char* req_mq, int min, int max, char* dir_path_name, char* outfile) {

pid_t pid;

/* get the process id */
if ((pid = getpid()) < 0) {
    perror("unable to get client pid");
}

mqd_t mqd, dq;

char pfx[50] = DQ_PRFX;
char suffix[50]; //
sprintf(suffix, "%d", pid);
strcat(pfx, suffix);

dq = mq_open(pfx, O_RDWR | O_CREAT, 0666, NULL);
if (dq == -1) {
    perror("can not open data queue\n");
    exit(1);
}
printf("data queue created, mq id = %d\n", (int) dq);

mqd = mq_open(req_mq, O_RDWR);
if (mqd == -1) {
    perror("can not open msg queue\n");
    exit(1);
}

mqdes and dq seem to share the same id 3.

+3  A: 

Think of a handle as an array index. An index into an array held by the operating system, one for every process in the system.

When you open a handle (be it for a file, message queue, socket, etc) the operating system records the settings for that object in an array that is unique for your process. The operating system then returns an index into that array to your program.

Every time your program uses that "handle" the operating system is really just looking up a structure in that private array it keeps to find out how to deal with the object related to that "handle".

Linux typically reserves handles 0, 1 and 2 for STDIN, STDOUT, and STDERR respectively. But from then on any handles you open will be numbered 3, 4, and so forth. And your handle 3 might relate to file "/tmp/foo.txt" while another process's handle 3 might relate to file "/tmp/bar.txt". So if two processes are using similar file "handles" it is irrelevant.

By the way, you shouldn't need to know, or care, about what a handle actually contains. In theory it could be anything - a magic number, a pointer, an integer, it doesn't matter. The handle is really a secret token that you just hand to the operating system any time you want access to your system object.

PP
+1 Maybe just a touch more emphasis between conceptualization and actual implementation differences.
Duck
+1  A: 

maybe you didn't close the first message queue. because in that situation os gives the same id (index) to the new one.

erasmus