Deleting message queue in Ubuntu C

75 Views Asked by At

I am trying to remove a recently created message queue in Ubuntu using C, and I can't seem to be able to do it.

#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/wait.h>
#include <unistd.h> 
#include <sys/msg.h>

typedef struct{
    long type;
    int age;
    char name[20];
}message;

int msgqid;

int main(){
    if(msgqid=msgget(IPC_PRIVATE, IPC_CREAT | 0600) == -1){
        printf("Error msgget");
        exit(3);
    }
    
    
    msgctl(msgqid,IPC_RMID,NULL);
}

I was intending to create the queue and then delete it, just to understand how it works and not saturate my computer, but it just creates it and remains there.

Edit: I did some error checking on the msgctl, and it seems it just works the first time I execute it. Every time after that, it just leaves the queue without removing it, even after removing the rest of the created queues.

1

There are 1 best solutions below

0
kjohri On

There is a bug in the if statement. A pair of parenthesis is required around the assignment of the return value of msgget in the if statement

#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/msg.h>

typedef struct{
    long type;
    int age;
    char name[20];
}message;

int msgqid;

int main(){
    if ((msgqid=msgget(IPC_PRIVATE, IPC_CREAT | 0600)) == -1){
        printf("Error msgget");
        exit(3);
    }

    printf ("Press ENTER to continue: ");
    getchar ();

    if (msgctl(msgqid,IPC_RMID,NULL) == -1) {
        perror ("msgctl");
        exit (1);
    }

}