1 /* Copyright 2002, Red Hat Inc. */
2
3 #include <mqueue.h>
4 #include <errno.h>
5 #include <fcntl.h>
6 #include <sys/stat.h>
7 #include <sys/mman.h>
8 #include <sys/ipc.h>
9 #include <sys/sem.h>
10 #include <string.h>
11 #include <stdlib.h>
12 #include <machine/weakalias.h>
13 #define _LIBC 1
14 #include <sys/lock.h>
15 #undef _LIBC
16
17 #include "mqlocal.h"
18
19 int
mq_unlink(const char * name)20 mq_unlink (const char *name)
21 {
22 int size;
23 int saved_errno;
24 char *real_name;
25 char *ptr;
26 int i, rc;
27 int semid, msgqid;
28 key_t key;
29
30 /* ignore opening slash if present */
31 if (*name == '/')
32 ++name;
33 size = strlen(name);
34
35 if ((real_name = (char *)malloc (size + sizeof(MSGQ_PREFIX))) == NULL)
36 {
37 errno = ENOSPC;
38 return -1;
39 }
40
41 /* use given name to create shared memory file name - we convert any
42 slashes to underscores so we don't have to create directories */
43 memcpy (real_name, MSGQ_PREFIX, sizeof(MSGQ_PREFIX) - 1);
44 memcpy (real_name + sizeof(MSGQ_PREFIX) - 1, name, size + 1);
45 ptr = real_name + sizeof(MSGQ_PREFIX) - 1;
46 for (i = 0; i < size; ++i)
47 {
48 if (*ptr == '/')
49 *ptr = '_';
50 ++ptr;
51 }
52
53 /* get key and then unlink shared memory file */
54 if ((key = ftok(real_name, 255)) == (key_t)-1)
55 return -1;
56
57 rc = unlink (real_name);
58
59 if (rc == 0)
60 {
61 /* try to remove semaphore and msg queues associated with shared memory file */
62 saved_errno = errno;
63 semid = semget (key, 6, 0);
64 if (semid != -1)
65 semctl (semid, 0, IPC_RMID);
66 msgqid = msgget (key, 0);
67 if (msgqid != -1)
68 msgctl (msgqid, IPC_RMID, NULL);
69 errno = saved_errno;
70 }
71
72 return rc;
73 }
74