refactor type checks and remove unnecessary guards
[ruby_posix_mq.git] / ext / posix_mq / posix_mq.c
blob26c451490de44a95f35ba7a25718f3ca664377d2
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) ((void)(0))
35 # define MQ_IO_NILP(mq) ((void)(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 sym_r, sym_w, sym_rw;
68 static const mqd_t MQD_INVALID = (mqd_t)-1;
70 /* Ruby 1.8.6+ macros (for compatibility with Ruby 1.9) */
71 #ifndef RSTRING_PTR
72 # define RSTRING_PTR(s) (RSTRING(s)->ptr)
73 #endif
74 #ifndef RSTRING_LEN
75 # define RSTRING_LEN(s) (RSTRING(s)->len)
76 #endif
77 #ifndef RSTRUCT_PTR
78 # define RSTRUCT_PTR(s) (RSTRUCT(s)->ptr)
79 #endif
80 #ifndef RSTRUCT_LEN
81 # define RSTRUCT_LEN(s) (RSTRUCT(s)->len)
82 #endif
84 #ifndef HAVE_RB_STR_SET_LEN
85 # ifdef RUBINIUS
86 # define rb_str_set_len(str,len) rb_str_resize(str,len)
87 # else /* 1.8.6 optimized version */
88 /* this is taken from Ruby 1.8.7, 1.8.6 may not have it */
89 static void rb_18_str_set_len(VALUE str, long len)
91 RSTRING(str)->len = len;
92 RSTRING(str)->ptr[len] = '\0';
94 # define rb_str_set_len(str,len) rb_18_str_set_len(str,len)
95 # endif /* ! RUBINIUS */
96 #endif /* !defined(HAVE_RB_STR_SET_LEN) */
98 #ifndef HAVE_RB_STRUCT_ALLOC_NOINIT
99 static VALUE rb_struct_alloc_noinit(VALUE class)
101 return rb_funcall(class, id_new, 0, 0);
103 #endif /* !defined(HAVE_RB_STRUCT_ALLOC_NOINIT) */
105 /* partial emulation of the 1.9 rb_thread_blocking_region under 1.8 */
106 #ifndef HAVE_RB_THREAD_BLOCKING_REGION
107 # include <rubysig.h>
108 # define RUBY_UBF_IO ((rb_unblock_function_t *)-1)
109 typedef void rb_unblock_function_t(void *);
110 typedef VALUE rb_blocking_function_t(void *);
111 static VALUE
112 rb_thread_blocking_region(
113 rb_blocking_function_t *func, void *data1,
114 rb_unblock_function_t *ubf, void *data2)
116 VALUE rv;
118 assert(RUBY_UBF_IO == ubf && "RUBY_UBF_IO required for emulation");
120 TRAP_BEG;
121 rv = func(data1);
122 TRAP_END;
124 return rv;
126 #endif /* ! HAVE_RB_THREAD_BLOCKING_REGION */
128 /* used to pass arguments to mq_open inside blocking region */
129 struct open_args {
130 int argc;
131 const char *name;
132 int oflags;
133 mode_t mode;
134 struct mq_attr attr;
137 /* used to pass arguments to mq_send/mq_receive inside blocking region */
138 struct rw_args {
139 mqd_t des;
140 char *msg_ptr;
141 size_t msg_len;
142 unsigned msg_prio;
143 struct timespec *timeout;
146 static void num2timespec(struct timespec *ts, VALUE t)
148 switch (TYPE(t)) {
149 case T_FIXNUM:
150 case T_BIGNUM:
151 ts->tv_sec = NUM2TIMET(t);
152 ts->tv_nsec = 0;
153 break;
154 case T_FLOAT: {
155 double f, d;
156 double val = RFLOAT_VALUE(t);
158 d = modf(val, &f);
159 if (d >= 0) {
160 ts->tv_nsec = (long)(d * 1e9 + 0.5);
161 } else {
162 ts->tv_nsec = (long)(-d * 1e9 + 0.5);
163 if (ts->tv_nsec > 0) {
164 ts->tv_nsec = 1000000000 - ts->tv_nsec;
165 f -= 1;
168 ts->tv_sec = (time_t)f;
169 if (f != ts->tv_sec)
170 rb_raise(rb_eRangeError, "%f out of range", val);
171 ts->tv_sec = (time_t)f;
173 break;
174 default: {
175 VALUE f;
176 VALUE ary = rb_funcall(t, id_divmod, 1, INT2FIX(1));
178 Check_Type(ary, T_ARRAY);
180 ts->tv_sec = NUM2TIMET(rb_ary_entry(ary, 0));
181 f = rb_ary_entry(ary, 1);
182 f = rb_funcall(f, id_mul, 1, INT2FIX(1000000000));
183 ts->tv_nsec = NUM2LONG(f);
188 static struct timespec *convert_timeout(struct timespec *dest, VALUE t)
190 struct timespec ts, now;
192 if (NIL_P(t))
193 return NULL;
195 num2timespec(&ts, t);
196 clock_gettime(CLOCK_REALTIME, &now);
197 dest->tv_sec = now.tv_sec + ts.tv_sec;
198 dest->tv_nsec = now.tv_nsec + ts.tv_nsec;
200 if (dest->tv_nsec > 1000000000) {
201 dest->tv_nsec -= 1000000000;
202 ++dest->tv_sec;
205 return dest;
208 /* (may) run without GVL */
209 static VALUE xopen(void *ptr)
211 struct open_args *x = ptr;
212 mqd_t rv;
214 switch (x->argc) {
215 case 2: rv = mq_open(x->name, x->oflags); break;
216 case 3: rv = mq_open(x->name, x->oflags, x->mode, NULL); break;
217 case 4: rv = mq_open(x->name, x->oflags, x->mode, &x->attr); break;
218 default: rv = MQD_INVALID;
221 return (VALUE)rv;
224 /* runs without GVL */
225 static VALUE xsend(void *ptr)
227 struct rw_args *x = ptr;
229 if (x->timeout)
230 return (VALUE)mq_timedsend(x->des, x->msg_ptr, x->msg_len,
231 x->msg_prio, x->timeout);
233 return (VALUE)mq_send(x->des, x->msg_ptr, x->msg_len, x->msg_prio);
236 /* runs without GVL */
237 static VALUE xrecv(void *ptr)
239 struct rw_args *x = ptr;
241 if (x->timeout)
242 return (VALUE)mq_timedreceive(x->des, x->msg_ptr, x->msg_len,
243 &x->msg_prio, x->timeout);
245 return (VALUE)mq_receive(x->des, x->msg_ptr, x->msg_len, &x->msg_prio);
248 /* called by GC */
249 static void mark(void *ptr)
251 struct posix_mq *mq = ptr;
253 rb_gc_mark(mq->name);
254 rb_gc_mark(mq->thread);
255 MQ_IO_MARK(mq);
258 /* called by GC */
259 static void _free(void *ptr)
261 struct posix_mq *mq = ptr;
263 if (mq->des != MQD_INVALID && MQ_IO_NIL_P(mq)) {
264 /* we ignore errors when gc-ing */
265 mq_close(mq->des);
266 errno = 0;
268 xfree(ptr);
271 /* automatically called at creation (before initialize) */
272 static VALUE alloc(VALUE klass)
274 struct posix_mq *mq;
275 VALUE rv = Data_Make_Struct(klass, struct posix_mq, mark, _free, mq);
277 mq->des = MQD_INVALID;
278 mq->attr.mq_flags = 0;
279 mq->attr.mq_maxmsg = 0;
280 mq->attr.mq_msgsize = -1;
281 mq->attr.mq_curmsgs = 0;
282 mq->name = Qnil;
283 mq->thread = Qnil;
284 MQ_IO_SET(mq, Qnil);
286 return rv;
289 /* unwraps the posix_mq struct from self */
290 static struct posix_mq *get(VALUE self, int need_valid)
292 struct posix_mq *mq;
294 Data_Get_Struct(self, struct posix_mq, mq);
296 if (need_valid && mq->des == MQD_INVALID)
297 rb_raise(rb_eIOError, "closed queue descriptor");
299 return mq;
302 static void check_struct_type(VALUE astruct)
304 if (CLASS_OF(astruct) == cAttr)
305 return;
306 astruct = rb_inspect(astruct);
307 rb_raise(rb_eTypeError, "not a POSIX_MQ::Attr: %s",
308 StringValuePtr(astruct));
311 /* converts the POSIX_MQ::Attr astruct into a struct mq_attr attr */
312 static void attr_from_struct(struct mq_attr *attr, VALUE astruct, int all)
314 VALUE *ptr;
316 check_struct_type(astruct);
317 ptr = RSTRUCT_PTR(astruct);
319 attr->mq_flags = NUM2LONG(ptr[0]);
321 if (all || !NIL_P(ptr[1]))
322 attr->mq_maxmsg = NUM2LONG(ptr[1]);
323 if (all || !NIL_P(ptr[2]))
324 attr->mq_msgsize = NUM2LONG(ptr[2]);
325 if (!NIL_P(ptr[3]))
326 attr->mq_curmsgs = NUM2LONG(ptr[3]);
330 * call-seq:
331 * POSIX_MQ.new(name [, flags [, mode [, mq_attr]]) => mq
333 * Opens a POSIX message queue given by +name+. +name+ should start
334 * with a slash ("/") for portable applications.
336 * If a Symbol is given in place of integer +flags+, then:
338 * * +:r+ is equivalent to IO::RDONLY
339 * * +:w+ is equivalent to IO::CREAT|IO::WRONLY
340 * * +:rw+ is equivalent to IO::CREAT|IO::RDWR
342 * +mode+ is an integer and only used when IO::CREAT is used.
343 * +mq_attr+ is a POSIX_MQ::Attr and only used if IO::CREAT is used.
344 * If +mq_attr+ is not specified when creating a queue, then the
345 * system defaults will be used.
347 * See the manpage for mq_open(3) for more details on this function.
349 static VALUE init(int argc, VALUE *argv, VALUE self)
351 struct posix_mq *mq = get(self, 0);
352 struct open_args x;
353 VALUE name, oflags, mode, attr;
355 rb_scan_args(argc, argv, "13", &name, &oflags, &mode, &attr);
357 if (TYPE(name) != T_STRING)
358 rb_raise(rb_eArgError, "name must be a string");
360 switch (TYPE(oflags)) {
361 case T_NIL:
362 x.oflags = O_RDONLY;
363 break;
364 case T_SYMBOL:
365 if (oflags == sym_r)
366 x.oflags = O_RDONLY;
367 else if (oflags == sym_w)
368 x.oflags = O_CREAT|O_WRONLY;
369 else if (oflags == sym_rw)
370 x.oflags = O_CREAT|O_RDWR;
371 else {
372 oflags = rb_inspect(oflags);
373 rb_raise(rb_eArgError,
374 "symbol must be :r, :w, or :rw: %s",
375 StringValuePtr(oflags));
377 break;
378 case T_BIGNUM:
379 case T_FIXNUM:
380 x.oflags = NUM2INT(oflags);
381 break;
382 default:
383 rb_raise(rb_eArgError, "flags must be an int, :r, :w, or :wr");
386 x.name = RSTRING_PTR(name);
387 x.argc = 2;
389 switch (TYPE(mode)) {
390 case T_FIXNUM:
391 x.argc = 3;
392 x.mode = NUM2UINT(mode);
393 break;
394 case T_NIL:
395 if (x.oflags & O_CREAT) {
396 x.argc = 3;
397 x.mode = 0666;
399 break;
400 default:
401 rb_raise(rb_eArgError, "mode not an integer");
404 switch (TYPE(attr)) {
405 case T_STRUCT:
406 x.argc = 4;
407 attr_from_struct(&x.attr, attr, 1);
409 /* principle of least surprise */
410 if (x.attr.mq_flags & O_NONBLOCK)
411 x.oflags |= O_NONBLOCK;
412 break;
413 case T_NIL:
414 break;
415 default:
416 check_struct_type(attr);
419 mq->des = (mqd_t)xopen(&x);
420 if (mq->des == MQD_INVALID) {
421 if (errno == ENOMEM || errno == EMFILE || errno == ENFILE) {
422 rb_gc();
423 mq->des = (mqd_t)xopen(&x);
425 if (mq->des == MQD_INVALID)
426 rb_sys_fail("mq_open");
429 mq->name = rb_str_dup(name);
430 if (x.oflags & O_NONBLOCK)
431 mq->attr.mq_flags = O_NONBLOCK;
433 return self;
437 * call-seq:
438 * POSIX_MQ.unlink(name) => 1
440 * Unlinks the message queue given by +name+. The queue will be destroyed
441 * when the last process with the queue open closes its queue descriptors.
443 static VALUE s_unlink(VALUE self, VALUE name)
445 mqd_t rv;
447 if (TYPE(name) != T_STRING)
448 rb_raise(rb_eArgError, "argument must be a string");
450 rv = mq_unlink(RSTRING_PTR(name));
451 if (rv == MQD_INVALID)
452 rb_sys_fail("mq_unlink");
454 return INT2NUM(1);
458 * call-seq:
459 * mq.unlink => mq
461 * Unlinks the message queue to prevent other processes from accessing it.
462 * All existing queue descriptors to this queue including those opened by
463 * other processes are unaffected. The queue will only be destroyed
464 * when the last process with open descriptors to this queue closes
465 * the descriptors.
467 static VALUE _unlink(VALUE self)
469 struct posix_mq *mq = get(self, 0);
470 mqd_t rv;
472 assert(TYPE(mq->name) == T_STRING && "mq->name is not a string");
474 rv = mq_unlink(RSTRING_PTR(mq->name));
475 if (rv == MQD_INVALID)
476 rb_sys_fail("mq_unlink");
478 return self;
481 static void setup_send_buffer(struct rw_args *x, VALUE buffer)
483 buffer = rb_obj_as_string(buffer);
484 x->msg_ptr = RSTRING_PTR(buffer);
485 x->msg_len = (size_t)RSTRING_LEN(buffer);
489 * call-seq:
490 * mq.send(string [,priority[, timeout]]) => nil
492 * Inserts the given +string+ into the message queue with an optional,
493 * unsigned integer +priority+. If the optional +timeout+ is specified,
494 * then Errno::ETIMEDOUT will be raised if the operation cannot complete
495 * before +timeout+ seconds has elapsed. Without +timeout+, this method
496 * may block until the queue is writable.
498 static VALUE _send(int argc, VALUE *argv, VALUE self)
500 struct posix_mq *mq = get(self, 1);
501 struct rw_args x;
502 VALUE buffer, prio, timeout;
503 mqd_t rv;
504 struct timespec expire;
506 rb_scan_args(argc, argv, "12", &buffer, &prio, &timeout);
508 setup_send_buffer(&x, buffer);
509 x.des = mq->des;
510 x.timeout = convert_timeout(&expire, timeout);
511 x.msg_prio = NIL_P(prio) ? 0 : NUM2UINT(prio);
513 if (mq->attr.mq_flags & O_NONBLOCK)
514 rv = (mqd_t)xsend(&x);
515 else
516 rv = (mqd_t)rb_thread_blocking_region(xsend, &x,
517 RUBY_UBF_IO, 0);
518 if (rv == MQD_INVALID)
519 rb_sys_fail("mq_send");
521 return Qnil;
525 * call-seq:
526 * mq << string => mq
528 * Inserts the given +string+ into the message queue with a
529 * default priority of 0 and no timeout.
531 static VALUE send0(VALUE self, VALUE buffer)
533 struct posix_mq *mq = get(self, 1);
534 struct rw_args x;
535 mqd_t rv;
537 setup_send_buffer(&x, buffer);
538 x.des = mq->des;
539 x.timeout = NULL;
540 x.msg_prio = 0;
542 if (mq->attr.mq_flags & O_NONBLOCK)
543 rv = (mqd_t)xsend(&x);
544 else
545 rv = (mqd_t)rb_thread_blocking_region(xsend, &x,
546 RUBY_UBF_IO, 0);
548 if (rv == MQD_INVALID)
549 rb_sys_fail("mq_send");
551 return self;
554 #ifdef MQD_TO_FD
556 * call-seq:
557 * mq.to_io => IO
559 * Returns an IO.select-able +IO+ object. This method is only available
560 * under Linux and FreeBSD and is not intended to be portable.
562 static VALUE to_io(VALUE self)
564 struct posix_mq *mq = get(self, 1);
565 int fd = MQD_TO_FD(mq->des);
567 if (NIL_P(mq->io))
568 mq->io = rb_funcall(rb_cIO, id_new, 1, INT2NUM(fd));
570 return mq->io;
572 #endif
574 static VALUE _receive(int wantarray, int argc, VALUE *argv, VALUE self);
577 * call-seq:
578 * mq.receive([buffer, [timeout]]) => [ message, priority ]
580 * Takes the highest priority message off the queue and returns
581 * an array containing the message as a String and the Integer
582 * priority of the message.
584 * If the optional +buffer+ is present, then it must be a String
585 * which will receive the data.
587 * If the optional +timeout+ is present, then it may be a Float
588 * or Integer specifying the timeout in seconds. Errno::ETIMEDOUT
589 * will be raised if +timeout+ has elapsed and there are no messages
590 * in the queue.
592 static VALUE receive(int argc, VALUE *argv, VALUE self)
594 return _receive(1, argc, argv, self);
598 * call-seq:
599 * mq.shift([buffer, [timeout]]) => message
601 * Takes the highest priority message off the queue and returns
602 * the message as a String.
604 * If the optional +buffer+ is present, then it must be a String
605 * which will receive the data.
607 * If the optional +timeout+ is present, then it may be a Float
608 * or Integer specifying the timeout in seconds. Errno::ETIMEDOUT
609 * will be raised if +timeout+ has elapsed and there are no messages
610 * in the queue.
612 static VALUE shift(int argc, VALUE *argv, VALUE self)
614 return _receive(0, argc, argv, self);
617 static VALUE _receive(int wantarray, int argc, VALUE *argv, VALUE self)
619 struct posix_mq *mq = get(self, 1);
620 struct rw_args x;
621 VALUE buffer, timeout;
622 ssize_t r;
623 struct timespec expire;
625 if (mq->attr.mq_msgsize < 0) {
626 if (mq_getattr(mq->des, &mq->attr) < 0)
627 rb_sys_fail("mq_getattr");
630 rb_scan_args(argc, argv, "02", &buffer, &timeout);
631 x.timeout = convert_timeout(&expire, timeout);
633 if (NIL_P(buffer)) {
634 buffer = rb_str_new(0, mq->attr.mq_msgsize);
635 } else {
636 StringValue(buffer);
637 rb_str_modify(buffer);
638 rb_str_resize(buffer, mq->attr.mq_msgsize);
640 OBJ_TAINT(buffer);
641 x.msg_ptr = RSTRING_PTR(buffer);
642 x.msg_len = (size_t)mq->attr.mq_msgsize;
643 x.des = mq->des;
645 if (mq->attr.mq_flags & O_NONBLOCK) {
646 r = (ssize_t)xrecv(&x);
647 } else {
648 r = (ssize_t)rb_thread_blocking_region(xrecv, &x,
649 RUBY_UBF_IO, 0);
651 if (r < 0)
652 rb_sys_fail("mq_receive");
654 rb_str_set_len(buffer, r);
656 if (wantarray)
657 return rb_ary_new3(2, buffer, UINT2NUM(x.msg_prio));
658 return buffer;
662 * call-seq:
663 * mq.attr => mq_attr
665 * Returns a POSIX_MQ::Attr struct containing the attributes
666 * of the message queue. See the mq_getattr(3) manpage for
667 * more details.
669 static VALUE getattr(VALUE self)
671 struct posix_mq *mq = get(self, 1);
672 VALUE astruct;
673 VALUE *ptr;
675 if (mq_getattr(mq->des, &mq->attr) < 0)
676 rb_sys_fail("mq_getattr");
678 astruct = rb_struct_alloc_noinit(cAttr);
679 ptr = RSTRUCT_PTR(astruct);
680 ptr[0] = LONG2NUM(mq->attr.mq_flags);
681 ptr[1] = LONG2NUM(mq->attr.mq_maxmsg);
682 ptr[2] = LONG2NUM(mq->attr.mq_msgsize);
683 ptr[3] = LONG2NUM(mq->attr.mq_curmsgs);
685 return astruct;
689 * call-seq:
690 * mq.attr = POSIX_MQ::Attr(IO::NONBLOCK) => mq_attr
692 * Only the IO::NONBLOCK flag may be set or unset (zero) in this manner.
693 * See the mq_setattr(3) manpage for more details.
695 * Consider using the POSIX_MQ#nonblock= method as it is easier and
696 * more natural to use.
698 static VALUE setattr(VALUE self, VALUE astruct)
700 struct posix_mq *mq = get(self, 1);
701 struct mq_attr newattr;
703 attr_from_struct(&newattr, astruct, 0);
705 if (mq_setattr(mq->des, &newattr, NULL) < 0)
706 rb_sys_fail("mq_setattr");
708 return astruct;
712 * call-seq:
713 * mq.close => nil
715 * Closes the underlying message queue descriptor.
716 * If this descriptor had a registered notification request, the request
717 * will be removed so another descriptor or process may register a
718 * notification request. Message queue descriptors are automatically
719 * closed by garbage collection.
721 static VALUE _close(VALUE self)
723 struct posix_mq *mq = get(self, 1);
725 if (! MQ_IO_CLOSE(mq)) {
726 if (mq_close(mq->des) == -1)
727 rb_sys_fail("mq_close");
729 mq->des = MQD_INVALID;
731 return Qnil;
735 * call-seq:
736 * mq.closed? => true or false
738 * Returns +true+ if the message queue descriptor is closed and therefore
739 * unusable, otherwise +false+
741 static VALUE closed(VALUE self)
743 struct posix_mq *mq = get(self, 0);
745 return mq->des == MQD_INVALID ? Qtrue : Qfalse;
749 * call-seq:
750 * mq.name => string
752 * Returns the string name of message queue associated with +mq+
754 static VALUE name(VALUE self)
756 struct posix_mq *mq = get(self, 0);
758 return rb_str_dup(mq->name);
761 static int lookup_sig(VALUE sig)
763 static VALUE list;
764 const char *ptr;
765 long len;
767 sig = rb_obj_as_string(sig);
768 len = RSTRING_LEN(sig);
769 ptr = RSTRING_PTR(sig);
771 if (len > 3 && !memcmp("SIG", ptr, 3))
772 sig = rb_str_new(ptr + 3, len - 3);
774 if (!list) {
775 VALUE mSignal = rb_const_get(rb_cObject, rb_intern("Signal"));
777 list = rb_funcall(mSignal, rb_intern("list"), 0, 0);
778 rb_global_variable(&list);
781 sig = rb_hash_aref(list, sig);
782 if (NIL_P(sig))
783 rb_raise(rb_eArgError, "invalid signal: %s\n", ptr);
785 return NUM2INT(sig);
789 * TODO: Under Linux, we could just use netlink directly
790 * the same way glibc does...
792 /* we spawn a thread just to write ONE byte into an fd (usually a pipe) */
793 static void thread_notify_fd(union sigval sv)
795 int fd = sv.sival_int;
797 while ((write(fd, "", 1) < 0) && (errno == EINTR || errno == EAGAIN));
800 static void my_mq_notify(mqd_t des, struct sigevent *not)
802 mqd_t rv = mq_notify(des, not);
804 if (rv == MQD_INVALID) {
805 if (errno == ENOMEM) {
806 rb_gc();
807 rv = mq_notify(des, not);
809 if (rv == MQD_INVALID)
810 rb_sys_fail("mq_notify");
814 /* :nodoc: */
815 static VALUE setnotify_exec(VALUE self, VALUE io, VALUE thr)
817 int fd = NUM2INT(rb_funcall(io, id_fileno, 0, 0));
818 struct posix_mq *mq = get(self, 1);
819 struct sigevent not;
820 pthread_attr_t attr;
822 errno = pthread_attr_init(&attr);
823 if (errno) rb_sys_fail("pthread_attr_init");
825 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
826 if (errno) rb_sys_fail("pthread_attr_setdetachstate");
828 #ifdef PTHREAD_STACK_MIN
829 (void)pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN);
830 #endif
832 not.sigev_notify = SIGEV_THREAD;
833 not.sigev_notify_function = thread_notify_fd;
834 not.sigev_notify_attributes = &attr;
835 not.sigev_value.sival_int = fd;
837 if (!NIL_P(mq->thread))
838 rb_funcall(mq->thread, id_kill, 0, 0);
839 mq->thread = thr;
841 my_mq_notify(mq->des, &not);
843 return thr;
846 /* :nodoc: */
847 static VALUE notify_cleanup(VALUE self)
849 struct posix_mq *mq = get(self, 1);
851 if (!NIL_P(mq->thread)) {
852 rb_funcall(mq->thread, id_kill, 0, 0);
853 mq->thread = Qnil;
855 return Qnil;
859 * call-seq:
860 * mq.notify = signal => signal
862 * Registers the notification request to deliver a given +signal+
863 * to the current process when message is received.
864 * If +signal+ is +nil+, it will unregister and disable the notification
865 * request to allow other processes to register a request.
866 * If +signal+ is +false+, it will register a no-op notification request
867 * which will prevent other processes from registering a notification.
868 * If +signal+ is an +IO+ object, it will spawn a thread upon the
869 * arrival of the next message and write one "\\0" byte to the file
870 * descriptor belonging to that IO object.
871 * Only one process may have a notification request for a queue
872 * at a time, Errno::EBUSY will be raised if there is already
873 * a notification request registration for the queue.
875 * Notifications are only fired once and processes must reregister
876 * for subsequent notifications.
878 * For readers of the mq_notify(3) manpage, passing +false+
879 * is equivalent to SIGEV_NONE, and passing +nil+ is equivalent
880 * of passing a NULL notification pointer to mq_notify(3).
882 static VALUE setnotify(VALUE self, VALUE arg)
884 struct posix_mq *mq = get(self, 1);
885 struct sigevent not;
886 struct sigevent * notification = &not;
887 VALUE rv = arg;
889 notify_cleanup(self);
890 not.sigev_notify = SIGEV_SIGNAL;
892 switch (TYPE(arg)) {
893 case T_FALSE:
894 not.sigev_notify = SIGEV_NONE;
895 break;
896 case T_NIL:
897 notification = NULL;
898 break;
899 case T_FIXNUM:
900 not.sigev_signo = NUM2INT(arg);
901 break;
902 case T_SYMBOL:
903 case T_STRING:
904 not.sigev_signo = lookup_sig(arg);
905 rv = INT2NUM(not.sigev_signo);
906 break;
907 default:
908 rb_raise(rb_eArgError, "must be a signal or nil");
911 my_mq_notify(mq->des, notification);
913 return rv;
917 * call-seq:
918 * mq.nonblock? => true or false
920 * Returns the current non-blocking state of the message queue descriptor.
922 static VALUE getnonblock(VALUE self)
924 struct posix_mq *mq = get(self, 1);
926 return mq->attr.mq_flags & O_NONBLOCK ? Qtrue : Qfalse;
930 * call-seq:
931 * mq.nonblock = boolean => boolean
933 * Enables or disables non-blocking operation for the message queue
934 * descriptor. Errno::EAGAIN will be raised in situations where
935 * the queue would block. This is not compatible with +timeout+
936 * arguments to POSIX_MQ#send and POSIX_MQ#receive.
938 static VALUE setnonblock(VALUE self, VALUE nb)
940 struct mq_attr newattr;
941 struct posix_mq *mq = get(self, 1);
943 if (nb == Qtrue)
944 newattr.mq_flags = O_NONBLOCK;
945 else if (nb == Qfalse)
946 newattr.mq_flags = 0;
947 else
948 rb_raise(rb_eArgError, "must be true or false");
950 if (mq_setattr(mq->des, &newattr, &mq->attr) < 0)
951 rb_sys_fail("mq_setattr");
953 mq->attr.mq_flags = newattr.mq_flags;
955 return nb;
958 void Init_posix_mq_ext(void)
960 cPOSIX_MQ = rb_define_class("POSIX_MQ", rb_cObject);
961 rb_define_alloc_func(cPOSIX_MQ, alloc);
962 cAttr = rb_const_get(cPOSIX_MQ, rb_intern("Attr"));
965 * The maximum number of open message descriptors supported
966 * by the system. This may be -1, in which case it is dynamically
967 * set at runtime. Consult your operating system documentation
968 * for system-specific information about this.
970 rb_define_const(cPOSIX_MQ, "OPEN_MAX",
971 LONG2NUM(sysconf(_SC_MQ_OPEN_MAX)));
974 * The maximum priority that may be specified for POSIX_MQ#send
975 * On POSIX-compliant systems, this is at least 31, but some
976 * systems allow higher limits.
977 * The minimum priority is always zero.
979 rb_define_const(cPOSIX_MQ, "PRIO_MAX",
980 LONG2NUM(sysconf(_SC_MQ_PRIO_MAX)));
982 rb_define_singleton_method(cPOSIX_MQ, "unlink", s_unlink, 1);
984 rb_define_method(cPOSIX_MQ, "initialize", init, -1);
985 rb_define_method(cPOSIX_MQ, "send", _send, -1);
986 rb_define_method(cPOSIX_MQ, "<<", send0, 1);
987 rb_define_method(cPOSIX_MQ, "receive", receive, -1);
988 rb_define_method(cPOSIX_MQ, "shift", shift, -1);
989 rb_define_method(cPOSIX_MQ, "attr", getattr, 0);
990 rb_define_method(cPOSIX_MQ, "attr=", setattr, 1);
991 rb_define_method(cPOSIX_MQ, "close", _close, 0);
992 rb_define_method(cPOSIX_MQ, "closed?", closed, 0);
993 rb_define_method(cPOSIX_MQ, "unlink", _unlink, 0);
994 rb_define_method(cPOSIX_MQ, "name", name, 0);
995 rb_define_method(cPOSIX_MQ, "notify=", setnotify, 1);
996 rb_define_method(cPOSIX_MQ, "nonblock=", setnonblock, 1);
997 rb_define_method(cPOSIX_MQ, "notify_exec", setnotify_exec, 2);
998 rb_define_method(cPOSIX_MQ, "notify_cleanup", notify_cleanup, 0);
999 rb_define_method(cPOSIX_MQ, "nonblock?", getnonblock, 0);
1000 #ifdef MQD_TO_FD
1001 rb_define_method(cPOSIX_MQ, "to_io", to_io, 0);
1002 #endif
1004 id_new = rb_intern("new");
1005 id_kill = rb_intern("kill");
1006 id_fileno = rb_intern("fileno");
1007 id_mul = rb_intern("*");
1008 id_divmod = rb_intern("divmod");
1009 sym_r = ID2SYM(rb_intern("r"));
1010 sym_w = ID2SYM(rb_intern("w"));
1011 sym_rw = ID2SYM(rb_intern("rw"));