Do not trust locally cached mq_flags
[ruby_posix_mq.git] / ext / posix_mq / posix_mq.c
blob0d96c082d1ce284be0f2db0f6599b302c66834dc
1 #define _XOPEN_SOURCE 600
2 #ifdef HAVE_SYS_SELECT_H
3 # include <sys/select.h>
4 #endif
5 #ifdef HAVE_SIGNAL_H
6 # include <signal.h>
7 #endif
8 #ifdef HAVE_PTHREAD_H
9 # include <pthread.h>
10 #endif
11 #include <ruby.h>
13 #ifndef NUM2TIMET
14 # define NUM2TIMET NUM2INT
15 #endif
17 #include <time.h>
18 #include <mqueue.h>
19 #include <fcntl.h>
20 #include <sys/stat.h>
21 #include <errno.h>
22 #include <assert.h>
23 #include <unistd.h>
24 #include <float.h>
25 #include <math.h>
27 #if defined(__linux__)
28 # define MQD_TO_FD(mqd) (int)(mqd)
29 #elif defined(HAVE___MQ_OSHANDLE) /* FreeBSD */
30 # define MQD_TO_FD(mqd) __mq_oshandle(mqd)
31 #else
32 # define MQ_IO_MARK(mq) ((void)(0))
33 # define MQ_IO_SET(mq,val) ((void)(0))
34 # define MQ_IO_CLOSE(mq) ((int)(0))
35 # define MQ_IO_NIL_P(mq) ((int)(1))
36 #endif
38 struct posix_mq {
39 mqd_t des;
40 struct mq_attr attr;
41 VALUE name;
42 VALUE thread;
43 #ifdef MQD_TO_FD
44 VALUE io;
45 #endif
48 #ifdef MQD_TO_FD
49 # define MQ_IO_MARK(mq) rb_gc_mark((mq)->io)
50 # define MQ_IO_SET(mq,val) do { (mq)->io = (val); } while (0)
51 # define MQ_IO_NIL_P(mq) NIL_P((mq)->io)
52 static int MQ_IO_CLOSE(struct posix_mq *mq)
54 if (NIL_P(mq->io))
55 return 0;
57 /* not safe during GC */
58 rb_io_close(mq->io);
59 mq->io = Qnil;
61 return 1;
63 #endif
65 static VALUE cPOSIX_MQ, cAttr;
66 static ID id_new, id_kill, id_fileno, id_mul, id_divmod;
67 static ID id_flags, id_maxmsg, id_msgsize, id_curmsgs;
68 static ID sym_r, sym_w, sym_rw;
69 static const mqd_t MQD_INVALID = (mqd_t)-1;
71 /* Ruby 1.8.6+ macros (for compatibility with Ruby 1.9) */
72 #ifndef RSTRING_PTR
73 # define RSTRING_PTR(s) (RSTRING(s)->ptr)
74 #endif
75 #ifndef RSTRING_LEN
76 # define RSTRING_LEN(s) (RSTRING(s)->len)
77 #endif
78 #ifndef RFLOAT_VALUE
79 # define RFLOAT_VALUE(f) (RFLOAT(f)->value)
80 #endif
82 #ifndef HAVE_RB_STR_SET_LEN
83 /* this is taken from Ruby 1.8.7, 1.8.6 may not have it */
84 # ifdef RUBINIUS
85 # error upgrade Rubinius, rb_str_set_len should be available
86 # endif
87 static void rb_18_str_set_len(VALUE str, long len)
89 RSTRING(str)->len = len;
90 RSTRING(str)->ptr[len] = '\0';
92 #define rb_str_set_len rb_18_str_set_len
93 #endif /* !defined(HAVE_RB_STR_SET_LEN) */
95 /* partial emulation of the 1.9 rb_thread_blocking_region under 1.8 */
96 #ifndef HAVE_RB_THREAD_BLOCKING_REGION
97 # include <rubysig.h>
98 # define RUBY_UBF_IO ((rb_unblock_function_t *)-1)
99 typedef void rb_unblock_function_t(void *);
100 typedef VALUE rb_blocking_function_t(void *);
101 static VALUE
102 rb_thread_blocking_region(
103 rb_blocking_function_t *func, void *data1,
104 rb_unblock_function_t *ubf, void *data2)
106 VALUE rv;
108 assert(RUBY_UBF_IO == ubf && "RUBY_UBF_IO required for emulation");
110 TRAP_BEG;
111 rv = func(data1);
112 TRAP_END;
114 return rv;
116 #endif /* ! HAVE_RB_THREAD_BLOCKING_REGION */
118 /* used to pass arguments to mq_open inside blocking region */
119 struct open_args {
120 int argc;
121 const char *name;
122 int oflags;
123 mode_t mode;
124 struct mq_attr attr;
127 /* used to pass arguments to mq_send/mq_receive inside blocking region */
128 struct rw_args {
129 mqd_t des;
130 char *msg_ptr;
131 size_t msg_len;
132 unsigned msg_prio;
133 struct timespec *timeout;
136 #ifndef HAVE_MQ_TIMEDSEND
137 static mqd_t
138 not_timedsend(mqd_t mqdes, const char *msg_ptr,
139 size_t msg_len, unsigned msg_prio,
140 const struct timespec *abs_timeout)
142 rb_bug("mq_timedsend workaround failed");
143 return (mqd_t)-1;
145 # define mq_timedsend not_timedsend
146 #endif
147 #ifndef HAVE_MQ_TIMEDRECEIVE
148 static ssize_t
149 not_timedreceive(mqd_t mqdes, char *msg_ptr,
150 size_t msg_len, unsigned *msg_prio,
151 const struct timespec *abs_timeout)
153 rb_bug("mq_timedreceive workaround failed");
154 return (mqd_t)-1;
156 # define mq_timedreceive not_timedreceive
157 #endif
159 #if defined(HAVE_MQ_TIMEDRECEIVE) && defined(HAVE_MQ_TIMEDSEND)
160 static void num2timespec(struct timespec *ts, VALUE t)
162 switch (TYPE(t)) {
163 case T_FIXNUM:
164 case T_BIGNUM:
165 ts->tv_sec = NUM2TIMET(t);
166 ts->tv_nsec = 0;
167 break;
168 case T_FLOAT: {
169 double f, d;
170 double val = RFLOAT_VALUE(t);
172 d = modf(val, &f);
173 if (d >= 0) {
174 ts->tv_nsec = (long)(d * 1e9 + 0.5);
175 } else {
176 ts->tv_nsec = (long)(-d * 1e9 + 0.5);
177 if (ts->tv_nsec > 0) {
178 ts->tv_nsec = 1000000000 - ts->tv_nsec;
179 f -= 1;
182 ts->tv_sec = (time_t)f;
183 if (f != ts->tv_sec)
184 rb_raise(rb_eRangeError, "%f out of range", val);
185 ts->tv_sec = (time_t)f;
187 break;
188 default: {
189 VALUE f;
190 VALUE ary = rb_funcall(t, id_divmod, 1, INT2FIX(1));
192 Check_Type(ary, T_ARRAY);
194 ts->tv_sec = NUM2TIMET(rb_ary_entry(ary, 0));
195 f = rb_ary_entry(ary, 1);
196 f = rb_funcall(f, id_mul, 1, INT2FIX(1000000000));
197 ts->tv_nsec = NUM2LONG(f);
201 #else
202 static void num2timespec(struct timespec *ts, VALUE t)
204 rb_raise(rb_eNotImpError,
205 "mq_timedsend and/or mq_timedreceive missing");
207 #endif
209 static struct timespec *convert_timeout(struct timespec *dest, VALUE t)
211 struct timespec ts, now;
213 if (NIL_P(t))
214 return NULL;
216 num2timespec(&ts, t);
217 clock_gettime(CLOCK_REALTIME, &now);
218 dest->tv_sec = now.tv_sec + ts.tv_sec;
219 dest->tv_nsec = now.tv_nsec + ts.tv_nsec;
221 if (dest->tv_nsec > 1000000000) {
222 dest->tv_nsec -= 1000000000;
223 ++dest->tv_sec;
226 return dest;
229 /* (may) run without GVL */
230 static VALUE xopen(void *ptr)
232 struct open_args *x = ptr;
233 mqd_t rv;
235 switch (x->argc) {
236 case 2: rv = mq_open(x->name, x->oflags); break;
237 case 3: rv = mq_open(x->name, x->oflags, x->mode, NULL); break;
238 case 4: rv = mq_open(x->name, x->oflags, x->mode, &x->attr); break;
239 default: rv = MQD_INVALID;
242 return (VALUE)rv;
245 /* runs without GVL */
246 static VALUE xsend(void *ptr)
248 struct rw_args *x = ptr;
250 if (x->timeout)
251 return (VALUE)mq_timedsend(x->des, x->msg_ptr, x->msg_len,
252 x->msg_prio, x->timeout);
254 return (VALUE)mq_send(x->des, x->msg_ptr, x->msg_len, x->msg_prio);
257 /* runs without GVL */
258 static VALUE xrecv(void *ptr)
260 struct rw_args *x = ptr;
262 if (x->timeout)
263 return (VALUE)mq_timedreceive(x->des, x->msg_ptr, x->msg_len,
264 &x->msg_prio, x->timeout);
266 return (VALUE)mq_receive(x->des, x->msg_ptr, x->msg_len, &x->msg_prio);
269 /* called by GC */
270 static void mark(void *ptr)
272 struct posix_mq *mq = ptr;
274 rb_gc_mark(mq->name);
275 rb_gc_mark(mq->thread);
276 MQ_IO_MARK(mq);
279 /* called by GC */
280 static void _free(void *ptr)
282 struct posix_mq *mq = ptr;
284 if (mq->des != MQD_INVALID && MQ_IO_NIL_P(mq)) {
285 /* we ignore errors when gc-ing */
286 mq_close(mq->des);
287 errno = 0;
289 xfree(ptr);
292 /* automatically called at creation (before initialize) */
293 static VALUE alloc(VALUE klass)
295 struct posix_mq *mq;
296 VALUE rv = Data_Make_Struct(klass, struct posix_mq, mark, _free, mq);
298 mq->des = MQD_INVALID;
299 mq->attr.mq_flags = 0;
300 mq->attr.mq_maxmsg = 0;
301 mq->attr.mq_msgsize = -1;
302 mq->attr.mq_curmsgs = 0;
303 mq->name = Qnil;
304 mq->thread = Qnil;
305 MQ_IO_SET(mq, Qnil);
307 return rv;
310 /* unwraps the posix_mq struct from self */
311 static struct posix_mq *get(VALUE self, int need_valid)
313 struct posix_mq *mq;
315 Data_Get_Struct(self, struct posix_mq, mq);
317 if (need_valid && mq->des == MQD_INVALID)
318 rb_raise(rb_eIOError, "closed queue descriptor");
320 return mq;
323 static void check_struct_type(VALUE astruct)
325 if (CLASS_OF(astruct) == cAttr)
326 return;
327 astruct = rb_inspect(astruct);
328 rb_raise(rb_eTypeError, "not a POSIX_MQ::Attr: %s",
329 StringValuePtr(astruct));
332 static void rstruct2mqattr(struct mq_attr *attr, VALUE astruct, int all)
334 VALUE tmp;
336 check_struct_type(astruct);
337 attr->mq_flags = NUM2LONG(rb_funcall(astruct, id_flags, 0));
339 tmp = rb_funcall(astruct, id_maxmsg, 0);
340 if (all || !NIL_P(tmp))
341 attr->mq_maxmsg = NUM2LONG(tmp);
343 tmp = rb_funcall(astruct, id_msgsize, 0);
344 if (all || !NIL_P(tmp))
345 attr->mq_msgsize = NUM2LONG(tmp);
347 tmp = rb_funcall(astruct, id_curmsgs, 0);
348 if (!NIL_P(tmp))
349 attr->mq_curmsgs = NUM2LONG(tmp);
353 * call-seq:
354 * POSIX_MQ.new(name [, flags [, mode [, mq_attr]]) => mq
356 * Opens a POSIX message queue given by +name+. +name+ should start
357 * with a slash ("/") for portable applications.
359 * If a Symbol is given in place of integer +flags+, then:
361 * * +:r+ is equivalent to IO::RDONLY
362 * * +:w+ is equivalent to IO::CREAT|IO::WRONLY
363 * * +:rw+ is equivalent to IO::CREAT|IO::RDWR
365 * +mode+ is an integer and only used when IO::CREAT is used.
366 * +mq_attr+ is a POSIX_MQ::Attr and only used if IO::CREAT is used.
367 * If +mq_attr+ is not specified when creating a queue, then the
368 * system defaults will be used.
370 * See the manpage for mq_open(3) for more details on this function.
372 static VALUE init(int argc, VALUE *argv, VALUE self)
374 struct posix_mq *mq = get(self, 0);
375 struct open_args x;
376 VALUE name, oflags, mode, attr;
378 rb_scan_args(argc, argv, "13", &name, &oflags, &mode, &attr);
380 switch (TYPE(oflags)) {
381 case T_NIL:
382 x.oflags = O_RDONLY;
383 break;
384 case T_SYMBOL:
385 if (oflags == sym_r)
386 x.oflags = O_RDONLY;
387 else if (oflags == sym_w)
388 x.oflags = O_CREAT|O_WRONLY;
389 else if (oflags == sym_rw)
390 x.oflags = O_CREAT|O_RDWR;
391 else {
392 oflags = rb_inspect(oflags);
393 rb_raise(rb_eArgError,
394 "symbol must be :r, :w, or :rw: %s",
395 StringValuePtr(oflags));
397 break;
398 case T_BIGNUM:
399 case T_FIXNUM:
400 x.oflags = NUM2INT(oflags);
401 break;
402 default:
403 rb_raise(rb_eArgError, "flags must be an int, :r, :w, or :wr");
406 x.name = StringValueCStr(name);
407 x.argc = 2;
409 switch (TYPE(mode)) {
410 case T_FIXNUM:
411 x.argc = 3;
412 x.mode = NUM2UINT(mode);
413 break;
414 case T_NIL:
415 if (x.oflags & O_CREAT) {
416 x.argc = 3;
417 x.mode = 0666;
419 break;
420 default:
421 rb_raise(rb_eArgError, "mode not an integer");
424 switch (TYPE(attr)) {
425 case T_STRUCT:
426 x.argc = 4;
427 rstruct2mqattr(&x.attr, attr, 1);
429 /* principle of least surprise */
430 if (x.attr.mq_flags & O_NONBLOCK)
431 x.oflags |= O_NONBLOCK;
432 break;
433 case T_NIL:
434 break;
435 default:
436 check_struct_type(attr);
439 mq->des = (mqd_t)xopen(&x);
440 if (mq->des == MQD_INVALID) {
441 if (errno == ENOMEM || errno == EMFILE || errno == ENFILE) {
442 rb_gc();
443 mq->des = (mqd_t)xopen(&x);
445 if (mq->des == MQD_INVALID)
446 rb_sys_fail("mq_open");
449 mq->name = rb_str_dup(name);
450 if (x.oflags & O_NONBLOCK)
451 mq->attr.mq_flags = O_NONBLOCK;
453 return self;
457 * call-seq:
458 * POSIX_MQ.unlink(name) => 1
460 * Unlinks the message queue given by +name+. The queue will be destroyed
461 * when the last process with the queue open closes its queue descriptors.
463 static VALUE s_unlink(VALUE self, VALUE name)
465 mqd_t rv = mq_unlink(StringValueCStr(name));
467 if (rv == MQD_INVALID)
468 rb_sys_fail("mq_unlink");
470 return INT2NUM(1);
474 * call-seq:
475 * mq.unlink => mq
477 * Unlinks the message queue to prevent other processes from accessing it.
478 * All existing queue descriptors to this queue including those opened by
479 * other processes are unaffected. The queue will only be destroyed
480 * when the last process with open descriptors to this queue closes
481 * the descriptors.
483 static VALUE _unlink(VALUE self)
485 struct posix_mq *mq = get(self, 0);
486 mqd_t rv;
488 assert(TYPE(mq->name) == T_STRING && "mq->name is not a string");
490 rv = mq_unlink(RSTRING_PTR(mq->name));
491 if (rv == MQD_INVALID)
492 rb_sys_fail("mq_unlink");
494 return self;
497 static void setup_send_buffer(struct rw_args *x, VALUE buffer)
499 buffer = rb_obj_as_string(buffer);
500 x->msg_ptr = RSTRING_PTR(buffer);
501 x->msg_len = (size_t)RSTRING_LEN(buffer);
505 * call-seq:
506 * mq.send(string [,priority[, timeout]]) => nil
508 * Inserts the given +string+ into the message queue with an optional,
509 * unsigned integer +priority+. If the optional +timeout+ is specified,
510 * then Errno::ETIMEDOUT will be raised if the operation cannot complete
511 * before +timeout+ seconds has elapsed. Without +timeout+, this method
512 * may block until the queue is writable.
514 * On some older systems, the +timeout+ argument is not currently
515 * supported and may raise NotImplementedError if +timeout+ is used.
517 static VALUE _send(int argc, VALUE *argv, VALUE self)
519 struct posix_mq *mq = get(self, 1);
520 struct rw_args x;
521 VALUE buffer, prio, timeout;
522 mqd_t rv;
523 struct timespec expire;
525 rb_scan_args(argc, argv, "12", &buffer, &prio, &timeout);
527 setup_send_buffer(&x, buffer);
528 x.des = mq->des;
529 x.timeout = convert_timeout(&expire, timeout);
530 x.msg_prio = NIL_P(prio) ? 0 : NUM2UINT(prio);
532 rv = (mqd_t)rb_thread_blocking_region(xsend, &x, RUBY_UBF_IO, 0);
533 if (rv == MQD_INVALID)
534 rb_sys_fail("mq_send");
536 return Qnil;
540 * call-seq:
541 * mq << string => mq
543 * Inserts the given +string+ into the message queue with a
544 * default priority of 0 and no timeout.
546 static VALUE send0(VALUE self, VALUE buffer)
548 struct posix_mq *mq = get(self, 1);
549 struct rw_args x;
550 mqd_t rv;
552 setup_send_buffer(&x, buffer);
553 x.des = mq->des;
554 x.timeout = NULL;
555 x.msg_prio = 0;
557 rv = (mqd_t)rb_thread_blocking_region(xsend, &x, RUBY_UBF_IO, 0);
558 if (rv == MQD_INVALID)
559 rb_sys_fail("mq_send");
561 return self;
564 #ifdef MQD_TO_FD
566 * call-seq:
567 * mq.to_io => IO
569 * Returns an IO.select-able +IO+ object. This method is only available
570 * under Linux and FreeBSD and is not intended to be portable.
572 static VALUE to_io(VALUE self)
574 struct posix_mq *mq = get(self, 1);
575 int fd = MQD_TO_FD(mq->des);
577 if (NIL_P(mq->io))
578 mq->io = rb_funcall(rb_cIO, id_new, 1, INT2NUM(fd));
580 return mq->io;
582 #endif
584 static VALUE _receive(int wantarray, int argc, VALUE *argv, VALUE self);
587 * call-seq:
588 * mq.receive([buffer, [timeout]]) => [ message, priority ]
590 * Takes the highest priority message off the queue and returns
591 * an array containing the message as a String and the Integer
592 * priority of the message.
594 * If the optional +buffer+ is present, then it must be a String
595 * which will receive the data.
597 * If the optional +timeout+ is present, then it may be a Float
598 * or Integer specifying the timeout in seconds. Errno::ETIMEDOUT
599 * will be raised if +timeout+ has elapsed and there are no messages
600 * in the queue.
602 * On some older systems, the +timeout+ argument is not currently
603 * supported and may raise NotImplementedError if +timeout+ is used.
605 static VALUE receive(int argc, VALUE *argv, VALUE self)
607 return _receive(1, argc, argv, self);
611 * call-seq:
612 * mq.shift([buffer, [timeout]]) => message
614 * Takes the highest priority message off the queue and returns
615 * the message as a String.
617 * If the optional +buffer+ is present, then it must be a String
618 * which will receive the data.
620 * If the optional +timeout+ is present, then it may be a Float
621 * or Integer specifying the timeout in seconds. Errno::ETIMEDOUT
622 * will be raised if +timeout+ has elapsed and there are no messages
623 * in the queue.
625 * On some older systems, the +timeout+ argument is not currently
626 * supported and may raise NotImplementedError if +timeout+ is used.
628 static VALUE shift(int argc, VALUE *argv, VALUE self)
630 return _receive(0, argc, argv, self);
633 static VALUE _receive(int wantarray, int argc, VALUE *argv, VALUE self)
635 struct posix_mq *mq = get(self, 1);
636 struct rw_args x;
637 VALUE buffer, timeout;
638 ssize_t r;
639 struct timespec expire;
641 if (mq->attr.mq_msgsize < 0) {
642 if (mq_getattr(mq->des, &mq->attr) < 0)
643 rb_sys_fail("mq_getattr");
646 rb_scan_args(argc, argv, "02", &buffer, &timeout);
647 x.timeout = convert_timeout(&expire, timeout);
649 if (NIL_P(buffer)) {
650 buffer = rb_str_new(0, mq->attr.mq_msgsize);
651 } else {
652 StringValue(buffer);
653 rb_str_modify(buffer);
654 rb_str_resize(buffer, mq->attr.mq_msgsize);
656 OBJ_TAINT(buffer);
657 x.msg_ptr = RSTRING_PTR(buffer);
658 x.msg_len = (size_t)mq->attr.mq_msgsize;
659 x.des = mq->des;
661 r = (ssize_t)rb_thread_blocking_region(xrecv, &x, RUBY_UBF_IO, 0);
662 if (r < 0)
663 rb_sys_fail("mq_receive");
665 rb_str_set_len(buffer, r);
667 if (wantarray)
668 return rb_ary_new3(2, buffer, UINT2NUM(x.msg_prio));
669 return buffer;
673 * call-seq:
674 * mq.attr => mq_attr
676 * Returns a POSIX_MQ::Attr struct containing the attributes
677 * of the message queue. See the mq_getattr(3) manpage for
678 * more details.
680 static VALUE getattr(VALUE self)
682 struct posix_mq *mq = get(self, 1);
683 VALUE astruct;
685 if (mq_getattr(mq->des, &mq->attr) < 0)
686 rb_sys_fail("mq_getattr");
688 return rb_funcall(cAttr, id_new, 4,
689 LONG2NUM(mq->attr.mq_flags),
690 LONG2NUM(mq->attr.mq_maxmsg),
691 LONG2NUM(mq->attr.mq_msgsize),
692 LONG2NUM(mq->attr.mq_curmsgs));
696 * call-seq:
697 * mq.attr = POSIX_MQ::Attr(IO::NONBLOCK) => mq_attr
699 * Only the IO::NONBLOCK flag may be set or unset (zero) in this manner.
700 * See the mq_setattr(3) manpage for more details.
702 * Consider using the POSIX_MQ#nonblock= method as it is easier and
703 * more natural to use.
705 static VALUE setattr(VALUE self, VALUE astruct)
707 struct posix_mq *mq = get(self, 1);
708 struct mq_attr newattr;
710 rstruct2mqattr(&newattr, astruct, 0);
712 if (mq_setattr(mq->des, &newattr, NULL) < 0)
713 rb_sys_fail("mq_setattr");
715 return astruct;
719 * call-seq:
720 * mq.close => nil
722 * Closes the underlying message queue descriptor.
723 * If this descriptor had a registered notification request, the request
724 * will be removed so another descriptor or process may register a
725 * notification request. Message queue descriptors are automatically
726 * closed by garbage collection.
728 static VALUE _close(VALUE self)
730 struct posix_mq *mq = get(self, 1);
732 if (! MQ_IO_CLOSE(mq)) {
733 if (mq_close(mq->des) == -1)
734 rb_sys_fail("mq_close");
736 mq->des = MQD_INVALID;
738 return Qnil;
742 * call-seq:
743 * mq.closed? => true or false
745 * Returns +true+ if the message queue descriptor is closed and therefore
746 * unusable, otherwise +false+
748 static VALUE closed(VALUE self)
750 struct posix_mq *mq = get(self, 0);
752 return mq->des == MQD_INVALID ? Qtrue : Qfalse;
756 * call-seq:
757 * mq.name => string
759 * Returns the string name of message queue associated with +mq+
761 static VALUE name(VALUE self)
763 struct posix_mq *mq = get(self, 0);
765 return rb_str_dup(mq->name);
768 static int lookup_sig(VALUE sig)
770 static VALUE list;
771 const char *ptr;
772 long len;
774 sig = rb_obj_as_string(sig);
775 len = RSTRING_LEN(sig);
776 ptr = RSTRING_PTR(sig);
778 if (len > 3 && !memcmp("SIG", ptr, 3))
779 sig = rb_str_new(ptr + 3, len - 3);
781 if (!list) {
782 VALUE mSignal = rb_const_get(rb_cObject, rb_intern("Signal"));
784 list = rb_funcall(mSignal, rb_intern("list"), 0, 0);
785 rb_global_variable(&list);
788 sig = rb_hash_aref(list, sig);
789 if (NIL_P(sig))
790 rb_raise(rb_eArgError, "invalid signal: %s\n", ptr);
792 return NUM2INT(sig);
796 * TODO: Under Linux, we could just use netlink directly
797 * the same way glibc does...
799 /* we spawn a thread just to write ONE byte into an fd (usually a pipe) */
800 static void thread_notify_fd(union sigval sv)
802 int fd = sv.sival_int;
804 while ((write(fd, "", 1) < 0) && (errno == EINTR || errno == EAGAIN));
807 static void my_mq_notify(mqd_t des, struct sigevent *not)
809 mqd_t rv = mq_notify(des, not);
811 if (rv == MQD_INVALID) {
812 if (errno == ENOMEM) {
813 rb_gc();
814 rv = mq_notify(des, not);
816 if (rv == MQD_INVALID)
817 rb_sys_fail("mq_notify");
821 /* :nodoc: */
822 static VALUE setnotify_exec(VALUE self, VALUE io, VALUE thr)
824 int fd = NUM2INT(rb_funcall(io, id_fileno, 0, 0));
825 struct posix_mq *mq = get(self, 1);
826 struct sigevent not;
827 pthread_attr_t attr;
829 errno = pthread_attr_init(&attr);
830 if (errno) rb_sys_fail("pthread_attr_init");
832 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
833 if (errno) rb_sys_fail("pthread_attr_setdetachstate");
835 #ifdef PTHREAD_STACK_MIN
836 (void)pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN);
837 #endif
839 not.sigev_notify = SIGEV_THREAD;
840 not.sigev_notify_function = thread_notify_fd;
841 not.sigev_notify_attributes = &attr;
842 not.sigev_value.sival_int = fd;
844 if (!NIL_P(mq->thread))
845 rb_funcall(mq->thread, id_kill, 0, 0);
846 mq->thread = thr;
848 my_mq_notify(mq->des, &not);
850 return thr;
853 /* :nodoc: */
854 static VALUE notify_cleanup(VALUE self)
856 struct posix_mq *mq = get(self, 1);
858 if (!NIL_P(mq->thread)) {
859 rb_funcall(mq->thread, id_kill, 0, 0);
860 mq->thread = Qnil;
862 return Qnil;
866 * call-seq:
867 * mq.notify = signal => signal
869 * Registers the notification request to deliver a given +signal+
870 * to the current process when message is received.
871 * If +signal+ is +nil+, it will unregister and disable the notification
872 * request to allow other processes to register a request.
873 * If +signal+ is +false+, it will register a no-op notification request
874 * which will prevent other processes from registering a notification.
875 * If +signal+ is an +IO+ object, it will spawn a thread upon the
876 * arrival of the next message and write one "\\0" byte to the file
877 * descriptor belonging to that IO object.
878 * Only one process may have a notification request for a queue
879 * at a time, Errno::EBUSY will be raised if there is already
880 * a notification request registration for the queue.
882 * Notifications are only fired once and processes must reregister
883 * for subsequent notifications.
885 * For readers of the mq_notify(3) manpage, passing +false+
886 * is equivalent to SIGEV_NONE, and passing +nil+ is equivalent
887 * of passing a NULL notification pointer to mq_notify(3).
889 static VALUE setnotify(VALUE self, VALUE arg)
891 struct posix_mq *mq = get(self, 1);
892 struct sigevent not;
893 struct sigevent * notification = &not;
894 VALUE rv = arg;
896 notify_cleanup(self);
897 not.sigev_notify = SIGEV_SIGNAL;
899 switch (TYPE(arg)) {
900 case T_FALSE:
901 not.sigev_notify = SIGEV_NONE;
902 break;
903 case T_NIL:
904 notification = NULL;
905 break;
906 case T_FIXNUM:
907 not.sigev_signo = NUM2INT(arg);
908 break;
909 case T_SYMBOL:
910 case T_STRING:
911 not.sigev_signo = lookup_sig(arg);
912 rv = INT2NUM(not.sigev_signo);
913 break;
914 default:
915 rb_raise(rb_eArgError, "must be a signal or nil");
918 my_mq_notify(mq->des, notification);
920 return rv;
924 * call-seq:
925 * mq.nonblock? => true or false
927 * Returns the current non-blocking state of the message queue descriptor.
929 static VALUE nonblock_p(VALUE self)
931 struct posix_mq *mq = get(self, 1);
933 if (mq_getattr(mq->des, &mq->attr) < 0)
934 rb_sys_fail("mq_getattr");
935 return mq->attr.mq_flags & O_NONBLOCK ? Qtrue : Qfalse;
939 * call-seq:
940 * mq.nonblock = boolean => boolean
942 * Enables or disables non-blocking operation for the message queue
943 * descriptor. Errno::EAGAIN will be raised in situations where
944 * the queue would block. This is not compatible with +timeout+
945 * arguments to POSIX_MQ#send and POSIX_MQ#receive.
947 static VALUE setnonblock(VALUE self, VALUE nb)
949 struct mq_attr newattr;
950 struct posix_mq *mq = get(self, 1);
952 if (nb == Qtrue)
953 newattr.mq_flags = O_NONBLOCK;
954 else if (nb == Qfalse)
955 newattr.mq_flags = 0;
956 else
957 rb_raise(rb_eArgError, "must be true or false");
959 if (mq_setattr(mq->des, &newattr, &mq->attr) < 0)
960 rb_sys_fail("mq_setattr");
962 mq->attr.mq_flags = newattr.mq_flags;
964 return nb;
967 void Init_posix_mq_ext(void)
969 cPOSIX_MQ = rb_define_class("POSIX_MQ", rb_cObject);
970 rb_define_alloc_func(cPOSIX_MQ, alloc);
971 cAttr = rb_const_get(cPOSIX_MQ, rb_intern("Attr"));
974 * The maximum number of open message descriptors supported
975 * by the system. This may be -1, in which case it is dynamically
976 * set at runtime. Consult your operating system documentation
977 * for system-specific information about this.
979 rb_define_const(cPOSIX_MQ, "OPEN_MAX",
980 LONG2NUM(sysconf(_SC_MQ_OPEN_MAX)));
983 * The maximum priority that may be specified for POSIX_MQ#send
984 * On POSIX-compliant systems, this is at least 31, but some
985 * systems allow higher limits.
986 * The minimum priority is always zero.
988 rb_define_const(cPOSIX_MQ, "PRIO_MAX",
989 LONG2NUM(sysconf(_SC_MQ_PRIO_MAX)));
991 rb_define_singleton_method(cPOSIX_MQ, "unlink", s_unlink, 1);
993 rb_define_method(cPOSIX_MQ, "initialize", init, -1);
994 rb_define_method(cPOSIX_MQ, "send", _send, -1);
995 rb_define_method(cPOSIX_MQ, "<<", send0, 1);
996 rb_define_method(cPOSIX_MQ, "receive", receive, -1);
997 rb_define_method(cPOSIX_MQ, "shift", shift, -1);
998 rb_define_method(cPOSIX_MQ, "attr", getattr, 0);
999 rb_define_method(cPOSIX_MQ, "attr=", setattr, 1);
1000 rb_define_method(cPOSIX_MQ, "close", _close, 0);
1001 rb_define_method(cPOSIX_MQ, "closed?", closed, 0);
1002 rb_define_method(cPOSIX_MQ, "unlink", _unlink, 0);
1003 rb_define_method(cPOSIX_MQ, "name", name, 0);
1004 rb_define_method(cPOSIX_MQ, "notify=", setnotify, 1);
1005 rb_define_method(cPOSIX_MQ, "nonblock=", setnonblock, 1);
1006 rb_define_method(cPOSIX_MQ, "notify_exec", setnotify_exec, 2);
1007 rb_define_method(cPOSIX_MQ, "notify_cleanup", notify_cleanup, 0);
1008 rb_define_method(cPOSIX_MQ, "nonblock?", nonblock_p, 0);
1009 #ifdef MQD_TO_FD
1010 rb_define_method(cPOSIX_MQ, "to_io", to_io, 0);
1011 #endif
1013 id_new = rb_intern("new");
1014 id_kill = rb_intern("kill");
1015 id_fileno = rb_intern("fileno");
1016 id_mul = rb_intern("*");
1017 id_divmod = rb_intern("divmod");
1018 id_flags = rb_intern("flags");
1019 id_maxmsg = rb_intern("maxmsg");
1020 id_msgsize = rb_intern("msgsize");
1021 id_curmsgs = rb_intern("curmsgs");
1022 sym_r = ID2SYM(rb_intern("r"));
1023 sym_w = ID2SYM(rb_intern("w"));
1024 sym_rw = ID2SYM(rb_intern("rw"));