3
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);
}

2 Answers 2

3

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.

0

More of a concern is the message queues themselves that have kernel persistence. Message queues are not removed until you remove them by calling mq_unlink(3) or reboot your system. There is a user ID related limit of how much memory can be allocated for message queues, which is enforced by mq_open(3) - see getrlimit(2) / setrlimit(2) manual page, resource RLIMIT_MSGQUEUE. In modern desktop or server machines the default limit is relatively low in terms of total available memory (ulimit -q gives 819200 for my off-the-shelf Ubuntu 12.04 / x86_64 installation with 16Gb of RAM memory), but there could be scenarios where not cleaning the unused message queues could create a malfunction for a user because kernel would refuse to allow opening any more message queues.

See mq_overview(7) manual page for reference (including links to the above mentioned manual pages).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.