Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly closing message queues best practices

gcc 4.72 c89

I am using this book as a reference to do mq_* posix message queues.

The Linux Programming Interface by Michael Kerrisk page 1071

However, in this example snippet I have noticed that they open a message queue get some attributes from the queue. However, they have failed to close it.

Isn't this bad practice as a resource leak could occur as all message queue descriptors could be used up if they are not returned to the OS? I guess when the process dies if would automatically return all resources back to the OS. However, if a process is running on a server 24/7 then this could have a major impact.

Many thanks for any suggestions,

int main(int argc, char *argv[])
{
    mqd_t mqd;
    struct mq_attr attr;
    if (argc != 2 || strcmp(argv[1], "--help") == 0)
        usageErr("%s mq-name\n", argv[0]);

    mqd = mq_open(argv[1], O_RDONLY);
    if (mqd == (mqd_t) -1)
        errExit("mq_open");

    if (mq_getattr(mqd, &attr) == -1)
        errExit("mq_getattr");

    printf("Maximum # of messages on queue: %ld\n", attr.mq_maxmsg);
    printf("Maximum message size: %ld\n", attr.mq_msgsize);
    printf("# of messages currently on queue: %ld\n", attr.mq_curmsgs);

    exit(EXIT_SUCCESS);
}
like image 269
ant2009 Avatar asked Oct 20 '25 10:10

ant2009


1 Answers

Yes, it is a bad practice.
But all the resources given to a process are reclaimed by the OS once the process exits.
In this case the resource only leaks for an insignificant amount of time,
between end of usage of queue and end of program, which is significantly small and hence immaterial.

In case of a continuously running process, you must clean all resources acquired explicitly or it results in a resource leak.

like image 152
Alok Save Avatar answered Oct 23 '25 00:10

Alok Save