fix for systems that can't convert mqd_t to FD
[ruby_posix_mq.git] / ext / posix_mq / posix_mq.c
blob1b5fde87ae7e43dfc52f4907480d9d17f6810531
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_NIL_P(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 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 #endif /* !defined(HAVE_RB_STR_SET_LEN) */
94 /* partial emulation of the 1.9 rb_thread_blocking_region under 1.8 */
95 #ifndef HAVE_RB_THREAD_BLOCKING_REGION
96 # include <rubysig.h>
97 # define RUBY_UBF_IO ((rb_unblock_function_t *)-1)
98 typedef void rb_unblock_function_t(void *);
99 typedef VALUE rb_blocking_function_t(void *);
100 static VALUE
101 rb_thread_blocking_region(
102 rb_blocking_function_t *func, void *data1,
103 rb_unblock_function_t *ubf, void *data2)
105 VALUE rv;
107 assert(RUBY_UBF_IO == ubf && "RUBY_UBF_IO required for emulation");
109 TRAP_BEG;
110 rv = func(data1);
111 TRAP_END;
113 return rv;
115 #endif /* ! HAVE_RB_THREAD_BLOCKING_REGION */
117 /* used to pass arguments to mq_open inside blocking region */
118 struct open_args {
119 int argc;
120 const char *name;
121 int oflags;
122 mode_t mode;
123 struct mq_attr attr;
126 /* used to pass arguments to mq_send/mq_receive inside blocking region */
127 struct rw_args {
128 mqd_t des;
129 char *msg_ptr;
130 size_t msg_len;
131 unsigned msg_prio;
132 struct timespec *timeout;
135 static void num2timespec(struct timespec *ts, VALUE t)
137 switch (TYPE(t)) {
138 case T_FIXNUM:
139 case T_BIGNUM:
140 ts->tv_sec = NUM2TIMET(t);
141 ts->tv_nsec = 0;
142 break;
143 case T_FLOAT: {
144 double f, d;
145 double val = RFLOAT_VALUE(t);
147 d = modf(val, &f);
148 if (d >= 0) {
149 ts->tv_nsec = (long)(d * 1e9 + 0.5);
150 } else {
151 ts->tv_nsec = (long)(-d * 1e9 + 0.5);
152 if (ts->tv_nsec > 0) {
153 ts->tv_nsec = 1000000000 - ts->tv_nsec;
154 f -= 1;
157 ts->tv_sec = (time_t)f;
158 if (f != ts->tv_sec)
159 rb_raise(rb_eRangeError, "%f out of range", val);
160 ts->tv_sec = (time_t)f;
162 break;
163 default: {
164 VALUE f;
165 VALUE ary = rb_funcall(t, id_divmod, 1, INT2FIX(1));
167 Check_Type(ary, T_ARRAY);
169 ts->tv_sec = NUM2TIMET(rb_ary_entry(ary, 0));
170 f = rb_ary_entry(ary, 1);
171 f = rb_funcall(f, id_mul, 1, INT2FIX(1000000000));
172 ts->tv_nsec = NUM2LONG(f);
177 static struct timespec *convert_timeout(struct timespec *dest, VALUE t)
179 struct timespec ts, now;
181 if (NIL_P(t))
182 return NULL;
184 num2timespec(&ts, t);
185 clock_gettime(CLOCK_REALTIME, &now);
186 dest->tv_sec = now.tv_sec + ts.tv_sec;
187 dest->tv_nsec = now.tv_nsec + ts.tv_nsec;
189 if (dest->tv_nsec > 1000000000) {
190 dest->tv_nsec -= 1000000000;
191 ++dest->tv_sec;
194 return dest;
197 /* (may) run without GVL */
198 static VALUE xopen(void *ptr)
200 struct open_args *x = ptr;
201 mqd_t rv;
203 switch (x->argc) {
204 case 2: rv = mq_open(x->name, x->oflags); break;
205 case 3: rv = mq_open(x->name, x->oflags, x->mode, NULL); break;
206 case 4: rv = mq_open(x->name, x->oflags, x->mode, &x->attr); break;
207 default: rv = MQD_INVALID;
210 return (VALUE)rv;
213 /* runs without GVL */
214 static VALUE xsend(void *ptr)
216 struct rw_args *x = ptr;
218 if (x->timeout)
219 return (VALUE)mq_timedsend(x->des, x->msg_ptr, x->msg_len,
220 x->msg_prio, x->timeout);
222 return (VALUE)mq_send(x->des, x->msg_ptr, x->msg_len, x->msg_prio);
225 /* runs without GVL */
226 static VALUE xrecv(void *ptr)
228 struct rw_args *x = ptr;
230 if (x->timeout)
231 return (VALUE)mq_timedreceive(x->des, x->msg_ptr, x->msg_len,
232 &x->msg_prio, x->timeout);
234 return (VALUE)mq_receive(x->des, x->msg_ptr, x->msg_len, &x->msg_prio);
237 /* called by GC */
238 static void mark(void *ptr)
240 struct posix_mq *mq = ptr;
242 rb_gc_mark(mq->name);
243 rb_gc_mark(mq->thread);
244 MQ_IO_MARK(mq);
247 /* called by GC */
248 static void _free(void *ptr)
250 struct posix_mq *mq = ptr;
252 if (mq->des != MQD_INVALID && MQ_IO_NIL_P(mq)) {
253 /* we ignore errors when gc-ing */
254 mq_close(mq->des);
255 errno = 0;
257 xfree(ptr);
260 /* automatically called at creation (before initialize) */
261 static VALUE alloc(VALUE klass)
263 struct posix_mq *mq;
264 VALUE rv = Data_Make_Struct(klass, struct posix_mq, mark, _free, mq);
266 mq->des = MQD_INVALID;
267 mq->attr.mq_flags = 0;
268 mq->attr.mq_maxmsg = 0;
269 mq->attr.mq_msgsize = -1;
270 mq->attr.mq_curmsgs = 0;
271 mq->name = Qnil;
272 mq->thread = Qnil;
273 MQ_IO_SET(mq, Qnil);
275 return rv;
278 /* unwraps the posix_mq struct from self */
279 static struct posix_mq *get(VALUE self, int need_valid)
281 struct posix_mq *mq;
283 Data_Get_Struct(self, struct posix_mq, mq);
285 if (need_valid && mq->des == MQD_INVALID)
286 rb_raise(rb_eIOError, "closed queue descriptor");
288 return mq;
291 static void check_struct_type(VALUE astruct)
293 if (CLASS_OF(astruct) == cAttr)
294 return;
295 astruct = rb_inspect(astruct);
296 rb_raise(rb_eTypeError, "not a POSIX_MQ::Attr: %s",
297 StringValuePtr(astruct));
300 static void rstruct2mqattr(struct mq_attr *attr, VALUE astruct, int all)
302 VALUE tmp;
304 check_struct_type(astruct);
305 attr->mq_flags = NUM2LONG(rb_funcall(astruct, id_flags, 0));
307 tmp = rb_funcall(astruct, id_maxmsg, 0);
308 if (all || !NIL_P(tmp))
309 attr->mq_maxmsg = NUM2LONG(tmp);
311 tmp = rb_funcall(astruct, id_msgsize, 0);
312 if (all || !NIL_P(tmp))
313 attr->mq_msgsize = NUM2LONG(tmp);
315 tmp = rb_funcall(astruct, id_curmsgs, 0);
316 if (!NIL_P(tmp))
317 attr->mq_curmsgs = NUM2LONG(tmp);
321 * call-seq:
322 * POSIX_MQ.new(name [, flags [, mode [, mq_attr]]) => mq
324 * Opens a POSIX message queue given by +name+. +name+ should start
325 * with a slash ("/") for portable applications.
327 * If a Symbol is given in place of integer +flags+, then:
329 * * +:r+ is equivalent to IO::RDONLY
330 * * +:w+ is equivalent to IO::CREAT|IO::WRONLY
331 * * +:rw+ is equivalent to IO::CREAT|IO::RDWR
333 * +mode+ is an integer and only used when IO::CREAT is used.
334 * +mq_attr+ is a POSIX_MQ::Attr and only used if IO::CREAT is used.
335 * If +mq_attr+ is not specified when creating a queue, then the
336 * system defaults will be used.
338 * See the manpage for mq_open(3) for more details on this function.
340 static VALUE init(int argc, VALUE *argv, VALUE self)
342 struct posix_mq *mq = get(self, 0);
343 struct open_args x;
344 VALUE name, oflags, mode, attr;
346 rb_scan_args(argc, argv, "13", &name, &oflags, &mode, &attr);
348 if (TYPE(name) != T_STRING)
349 rb_raise(rb_eArgError, "name must be a string");
351 switch (TYPE(oflags)) {
352 case T_NIL:
353 x.oflags = O_RDONLY;
354 break;
355 case T_SYMBOL:
356 if (oflags == sym_r)
357 x.oflags = O_RDONLY;
358 else if (oflags == sym_w)
359 x.oflags = O_CREAT|O_WRONLY;
360 else if (oflags == sym_rw)
361 x.oflags = O_CREAT|O_RDWR;
362 else {
363 oflags = rb_inspect(oflags);
364 rb_raise(rb_eArgError,
365 "symbol must be :r, :w, or :rw: %s",
366 StringValuePtr(oflags));
368 break;
369 case T_BIGNUM:
370 case T_FIXNUM:
371 x.oflags = NUM2INT(oflags);
372 break;
373 default:
374 rb_raise(rb_eArgError, "flags must be an int, :r, :w, or :wr");
377 x.name = RSTRING_PTR(name);
378 x.argc = 2;
380 switch (TYPE(mode)) {
381 case T_FIXNUM:
382 x.argc = 3;
383 x.mode = NUM2UINT(mode);
384 break;
385 case T_NIL:
386 if (x.oflags & O_CREAT) {
387 x.argc = 3;
388 x.mode = 0666;
390 break;
391 default:
392 rb_raise(rb_eArgError, "mode not an integer");
395 switch (TYPE(attr)) {
396 case T_STRUCT:
397 x.argc = 4;
398 rstruct2mqattr(&x.attr, attr, 1);
400 /* principle of least surprise */
401 if (x.attr.mq_flags & O_NONBLOCK)
402 x.oflags |= O_NONBLOCK;
403 break;
404 case T_NIL:
405 break;
406 default:
407 check_struct_type(attr);
410 mq->des = (mqd_t)xopen(&x);
411 if (mq->des == MQD_INVALID) {
412 if (errno == ENOMEM || errno == EMFILE || errno == ENFILE) {
413 rb_gc();
414 mq->des = (mqd_t)xopen(&x);
416 if (mq->des == MQD_INVALID)
417 rb_sys_fail("mq_open");
420 mq->name = rb_str_dup(name);
421 if (x.oflags & O_NONBLOCK)
422 mq->attr.mq_flags = O_NONBLOCK;
424 return self;
428 * call-seq:
429 * POSIX_MQ.unlink(name) => 1
431 * Unlinks the message queue given by +name+. The queue will be destroyed
432 * when the last process with the queue open closes its queue descriptors.
434 static VALUE s_unlink(VALUE self, VALUE name)
436 mqd_t rv;
438 if (TYPE(name) != T_STRING)
439 rb_raise(rb_eArgError, "argument must be a string");
441 rv = mq_unlink(RSTRING_PTR(name));
442 if (rv == MQD_INVALID)
443 rb_sys_fail("mq_unlink");
445 return INT2NUM(1);
449 * call-seq:
450 * mq.unlink => mq
452 * Unlinks the message queue to prevent other processes from accessing it.
453 * All existing queue descriptors to this queue including those opened by
454 * other processes are unaffected. The queue will only be destroyed
455 * when the last process with open descriptors to this queue closes
456 * the descriptors.
458 static VALUE _unlink(VALUE self)
460 struct posix_mq *mq = get(self, 0);
461 mqd_t rv;
463 assert(TYPE(mq->name) == T_STRING && "mq->name is not a string");
465 rv = mq_unlink(RSTRING_PTR(mq->name));
466 if (rv == MQD_INVALID)
467 rb_sys_fail("mq_unlink");
469 return self;
472 static void setup_send_buffer(struct rw_args *x, VALUE buffer)
474 buffer = rb_obj_as_string(buffer);
475 x->msg_ptr = RSTRING_PTR(buffer);
476 x->msg_len = (size_t)RSTRING_LEN(buffer);
480 * call-seq:
481 * mq.send(string [,priority[, timeout]]) => nil
483 * Inserts the given +string+ into the message queue with an optional,
484 * unsigned integer +priority+. If the optional +timeout+ is specified,
485 * then Errno::ETIMEDOUT will be raised if the operation cannot complete
486 * before +timeout+ seconds has elapsed. Without +timeout+, this method
487 * may block until the queue is writable.
489 static VALUE _send(int argc, VALUE *argv, VALUE self)
491 struct posix_mq *mq = get(self, 1);
492 struct rw_args x;
493 VALUE buffer, prio, timeout;
494 mqd_t rv;
495 struct timespec expire;
497 rb_scan_args(argc, argv, "12", &buffer, &prio, &timeout);
499 setup_send_buffer(&x, buffer);
500 x.des = mq->des;
501 x.timeout = convert_timeout(&expire, timeout);
502 x.msg_prio = NIL_P(prio) ? 0 : NUM2UINT(prio);
504 if (mq->attr.mq_flags & O_NONBLOCK)
505 rv = (mqd_t)xsend(&x);
506 else
507 rv = (mqd_t)rb_thread_blocking_region(xsend, &x,
508 RUBY_UBF_IO, 0);
509 if (rv == MQD_INVALID)
510 rb_sys_fail("mq_send");
512 return Qnil;
516 * call-seq:
517 * mq << string => mq
519 * Inserts the given +string+ into the message queue with a
520 * default priority of 0 and no timeout.
522 static VALUE send0(VALUE self, VALUE buffer)
524 struct posix_mq *mq = get(self, 1);
525 struct rw_args x;
526 mqd_t rv;
528 setup_send_buffer(&x, buffer);
529 x.des = mq->des;
530 x.timeout = NULL;
531 x.msg_prio = 0;
533 if (mq->attr.mq_flags & O_NONBLOCK)
534 rv = (mqd_t)xsend(&x);
535 else
536 rv = (mqd_t)rb_thread_blocking_region(xsend, &x,
537 RUBY_UBF_IO, 0);
539 if (rv == MQD_INVALID)
540 rb_sys_fail("mq_send");
542 return self;
545 #ifdef MQD_TO_FD
547 * call-seq:
548 * mq.to_io => IO
550 * Returns an IO.select-able +IO+ object. This method is only available
551 * under Linux and FreeBSD and is not intended to be portable.
553 static VALUE to_io(VALUE self)
555 struct posix_mq *mq = get(self, 1);
556 int fd = MQD_TO_FD(mq->des);
558 if (NIL_P(mq->io))
559 mq->io = rb_funcall(rb_cIO, id_new, 1, INT2NUM(fd));
561 return mq->io;
563 #endif
565 static VALUE _receive(int wantarray, int argc, VALUE *argv, VALUE self);
568 * call-seq:
569 * mq.receive([buffer, [timeout]]) => [ message, priority ]
571 * Takes the highest priority message off the queue and returns
572 * an array containing the message as a String and the Integer
573 * priority of the message.
575 * If the optional +buffer+ is present, then it must be a String
576 * which will receive the data.
578 * If the optional +timeout+ is present, then it may be a Float
579 * or Integer specifying the timeout in seconds. Errno::ETIMEDOUT
580 * will be raised if +timeout+ has elapsed and there are no messages
581 * in the queue.
583 static VALUE receive(int argc, VALUE *argv, VALUE self)
585 return _receive(1, argc, argv, self);
589 * call-seq:
590 * mq.shift([buffer, [timeout]]) => message
592 * Takes the highest priority message off the queue and returns
593 * the message as a String.
595 * If the optional +buffer+ is present, then it must be a String
596 * which will receive the data.
598 * If the optional +timeout+ is present, then it may be a Float
599 * or Integer specifying the timeout in seconds. Errno::ETIMEDOUT
600 * will be raised if +timeout+ has elapsed and there are no messages
601 * in the queue.
603 static VALUE shift(int argc, VALUE *argv, VALUE self)
605 return _receive(0, argc, argv, self);
608 static VALUE _receive(int wantarray, int argc, VALUE *argv, VALUE self)
610 struct posix_mq *mq = get(self, 1);
611 struct rw_args x;
612 VALUE buffer, timeout;
613 ssize_t r;
614 struct timespec expire;
616 if (mq->attr.mq_msgsize < 0) {
617 if (mq_getattr(mq->des, &mq->attr) < 0)
618 rb_sys_fail("mq_getattr");
621 rb_scan_args(argc, argv, "02", &buffer, &timeout);
622 x.timeout = convert_timeout(&expire, timeout);
624 if (NIL_P(buffer)) {
625 buffer = rb_str_new(0, mq->attr.mq_msgsize);
626 } else {
627 StringValue(buffer);
628 rb_str_modify(buffer);
629 rb_str_resize(buffer, mq->attr.mq_msgsize);
631 OBJ_TAINT(buffer);
632 x.msg_ptr = RSTRING_PTR(buffer);
633 x.msg_len = (size_t)mq->attr.mq_msgsize;
634 x.des = mq->des;
636 if (mq->attr.mq_flags & O_NONBLOCK) {
637 r = (ssize_t)xrecv(&x);
638 } else {
639 r = (ssize_t)rb_thread_blocking_region(xrecv, &x,
640 RUBY_UBF_IO, 0);
642 if (r < 0)
643 rb_sys_fail("mq_receive");
645 rb_str_set_len(buffer, r);
647 if (wantarray)
648 return rb_ary_new3(2, buffer, UINT2NUM(x.msg_prio));
649 return buffer;
653 * call-seq:
654 * mq.attr => mq_attr
656 * Returns a POSIX_MQ::Attr struct containing the attributes
657 * of the message queue. See the mq_getattr(3) manpage for
658 * more details.
660 static VALUE getattr(VALUE self)
662 struct posix_mq *mq = get(self, 1);
663 VALUE astruct;
665 if (mq_getattr(mq->des, &mq->attr) < 0)
666 rb_sys_fail("mq_getattr");
668 return rb_funcall(cAttr, id_new, 4,
669 LONG2NUM(mq->attr.mq_flags),
670 LONG2NUM(mq->attr.mq_maxmsg),
671 LONG2NUM(mq->attr.mq_msgsize),
672 LONG2NUM(mq->attr.mq_curmsgs));
676 * call-seq:
677 * mq.attr = POSIX_MQ::Attr(IO::NONBLOCK) => mq_attr
679 * Only the IO::NONBLOCK flag may be set or unset (zero) in this manner.
680 * See the mq_setattr(3) manpage for more details.
682 * Consider using the POSIX_MQ#nonblock= method as it is easier and
683 * more natural to use.
685 static VALUE setattr(VALUE self, VALUE astruct)
687 struct posix_mq *mq = get(self, 1);
688 struct mq_attr newattr;
690 rstruct2mqattr(&newattr, astruct, 0);
692 if (mq_setattr(mq->des, &newattr, NULL) < 0)
693 rb_sys_fail("mq_setattr");
695 return astruct;
699 * call-seq:
700 * mq.close => nil
702 * Closes the underlying message queue descriptor.
703 * If this descriptor had a registered notification request, the request
704 * will be removed so another descriptor or process may register a
705 * notification request. Message queue descriptors are automatically
706 * closed by garbage collection.
708 static VALUE _close(VALUE self)
710 struct posix_mq *mq = get(self, 1);
712 if (! MQ_IO_CLOSE(mq)) {
713 if (mq_close(mq->des) == -1)
714 rb_sys_fail("mq_close");
716 mq->des = MQD_INVALID;
718 return Qnil;
722 * call-seq:
723 * mq.closed? => true or false
725 * Returns +true+ if the message queue descriptor is closed and therefore
726 * unusable, otherwise +false+
728 static VALUE closed(VALUE self)
730 struct posix_mq *mq = get(self, 0);
732 return mq->des == MQD_INVALID ? Qtrue : Qfalse;
736 * call-seq:
737 * mq.name => string
739 * Returns the string name of message queue associated with +mq+
741 static VALUE name(VALUE self)
743 struct posix_mq *mq = get(self, 0);
745 return rb_str_dup(mq->name);
748 static int lookup_sig(VALUE sig)
750 static VALUE list;
751 const char *ptr;
752 long len;
754 sig = rb_obj_as_string(sig);
755 len = RSTRING_LEN(sig);
756 ptr = RSTRING_PTR(sig);
758 if (len > 3 && !memcmp("SIG", ptr, 3))
759 sig = rb_str_new(ptr + 3, len - 3);
761 if (!list) {
762 VALUE mSignal = rb_const_get(rb_cObject, rb_intern("Signal"));
764 list = rb_funcall(mSignal, rb_intern("list"), 0, 0);
765 rb_global_variable(&list);
768 sig = rb_hash_aref(list, sig);
769 if (NIL_P(sig))
770 rb_raise(rb_eArgError, "invalid signal: %s\n", ptr);
772 return NUM2INT(sig);
776 * TODO: Under Linux, we could just use netlink directly
777 * the same way glibc does...
779 /* we spawn a thread just to write ONE byte into an fd (usually a pipe) */
780 static void thread_notify_fd(union sigval sv)
782 int fd = sv.sival_int;
784 while ((write(fd, "", 1) < 0) && (errno == EINTR || errno == EAGAIN));
787 static void my_mq_notify(mqd_t des, struct sigevent *not)
789 mqd_t rv = mq_notify(des, not);
791 if (rv == MQD_INVALID) {
792 if (errno == ENOMEM) {
793 rb_gc();
794 rv = mq_notify(des, not);
796 if (rv == MQD_INVALID)
797 rb_sys_fail("mq_notify");
801 /* :nodoc: */
802 static VALUE setnotify_exec(VALUE self, VALUE io, VALUE thr)
804 int fd = NUM2INT(rb_funcall(io, id_fileno, 0, 0));
805 struct posix_mq *mq = get(self, 1);
806 struct sigevent not;
807 pthread_attr_t attr;
809 errno = pthread_attr_init(&attr);
810 if (errno) rb_sys_fail("pthread_attr_init");
812 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
813 if (errno) rb_sys_fail("pthread_attr_setdetachstate");
815 #ifdef PTHREAD_STACK_MIN
816 (void)pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN);
817 #endif
819 not.sigev_notify = SIGEV_THREAD;
820 not.sigev_notify_function = thread_notify_fd;
821 not.sigev_notify_attributes = &attr;
822 not.sigev_value.sival_int = fd;
824 if (!NIL_P(mq->thread))
825 rb_funcall(mq->thread, id_kill, 0, 0);
826 mq->thread = thr;
828 my_mq_notify(mq->des, &not);
830 return thr;
833 /* :nodoc: */
834 static VALUE notify_cleanup(VALUE self)
836 struct posix_mq *mq = get(self, 1);
838 if (!NIL_P(mq->thread)) {
839 rb_funcall(mq->thread, id_kill, 0, 0);
840 mq->thread = Qnil;
842 return Qnil;
846 * call-seq:
847 * mq.notify = signal => signal
849 * Registers the notification request to deliver a given +signal+
850 * to the current process when message is received.
851 * If +signal+ is +nil+, it will unregister and disable the notification
852 * request to allow other processes to register a request.
853 * If +signal+ is +false+, it will register a no-op notification request
854 * which will prevent other processes from registering a notification.
855 * If +signal+ is an +IO+ object, it will spawn a thread upon the
856 * arrival of the next message and write one "\\0" byte to the file
857 * descriptor belonging to that IO object.
858 * Only one process may have a notification request for a queue
859 * at a time, Errno::EBUSY will be raised if there is already
860 * a notification request registration for the queue.
862 * Notifications are only fired once and processes must reregister
863 * for subsequent notifications.
865 * For readers of the mq_notify(3) manpage, passing +false+
866 * is equivalent to SIGEV_NONE, and passing +nil+ is equivalent
867 * of passing a NULL notification pointer to mq_notify(3).
869 static VALUE setnotify(VALUE self, VALUE arg)
871 struct posix_mq *mq = get(self, 1);
872 struct sigevent not;
873 struct sigevent * notification = &not;
874 VALUE rv = arg;
876 notify_cleanup(self);
877 not.sigev_notify = SIGEV_SIGNAL;
879 switch (TYPE(arg)) {
880 case T_FALSE:
881 not.sigev_notify = SIGEV_NONE;
882 break;
883 case T_NIL:
884 notification = NULL;
885 break;
886 case T_FIXNUM:
887 not.sigev_signo = NUM2INT(arg);
888 break;
889 case T_SYMBOL:
890 case T_STRING:
891 not.sigev_signo = lookup_sig(arg);
892 rv = INT2NUM(not.sigev_signo);
893 break;
894 default:
895 rb_raise(rb_eArgError, "must be a signal or nil");
898 my_mq_notify(mq->des, notification);
900 return rv;
904 * call-seq:
905 * mq.nonblock? => true or false
907 * Returns the current non-blocking state of the message queue descriptor.
909 static VALUE getnonblock(VALUE self)
911 struct posix_mq *mq = get(self, 1);
913 return mq->attr.mq_flags & O_NONBLOCK ? Qtrue : Qfalse;
917 * call-seq:
918 * mq.nonblock = boolean => boolean
920 * Enables or disables non-blocking operation for the message queue
921 * descriptor. Errno::EAGAIN will be raised in situations where
922 * the queue would block. This is not compatible with +timeout+
923 * arguments to POSIX_MQ#send and POSIX_MQ#receive.
925 static VALUE setnonblock(VALUE self, VALUE nb)
927 struct mq_attr newattr;
928 struct posix_mq *mq = get(self, 1);
930 if (nb == Qtrue)
931 newattr.mq_flags = O_NONBLOCK;
932 else if (nb == Qfalse)
933 newattr.mq_flags = 0;
934 else
935 rb_raise(rb_eArgError, "must be true or false");
937 if (mq_setattr(mq->des, &newattr, &mq->attr) < 0)
938 rb_sys_fail("mq_setattr");
940 mq->attr.mq_flags = newattr.mq_flags;
942 return nb;
945 void Init_posix_mq_ext(void)
947 cPOSIX_MQ = rb_define_class("POSIX_MQ", rb_cObject);
948 rb_define_alloc_func(cPOSIX_MQ, alloc);
949 cAttr = rb_const_get(cPOSIX_MQ, rb_intern("Attr"));
952 * The maximum number of open message descriptors supported
953 * by the system. This may be -1, in which case it is dynamically
954 * set at runtime. Consult your operating system documentation
955 * for system-specific information about this.
957 rb_define_const(cPOSIX_MQ, "OPEN_MAX",
958 LONG2NUM(sysconf(_SC_MQ_OPEN_MAX)));
961 * The maximum priority that may be specified for POSIX_MQ#send
962 * On POSIX-compliant systems, this is at least 31, but some
963 * systems allow higher limits.
964 * The minimum priority is always zero.
966 rb_define_const(cPOSIX_MQ, "PRIO_MAX",
967 LONG2NUM(sysconf(_SC_MQ_PRIO_MAX)));
969 rb_define_singleton_method(cPOSIX_MQ, "unlink", s_unlink, 1);
971 rb_define_method(cPOSIX_MQ, "initialize", init, -1);
972 rb_define_method(cPOSIX_MQ, "send", _send, -1);
973 rb_define_method(cPOSIX_MQ, "<<", send0, 1);
974 rb_define_method(cPOSIX_MQ, "receive", receive, -1);
975 rb_define_method(cPOSIX_MQ, "shift", shift, -1);
976 rb_define_method(cPOSIX_MQ, "attr", getattr, 0);
977 rb_define_method(cPOSIX_MQ, "attr=", setattr, 1);
978 rb_define_method(cPOSIX_MQ, "close", _close, 0);
979 rb_define_method(cPOSIX_MQ, "closed?", closed, 0);
980 rb_define_method(cPOSIX_MQ, "unlink", _unlink, 0);
981 rb_define_method(cPOSIX_MQ, "name", name, 0);
982 rb_define_method(cPOSIX_MQ, "notify=", setnotify, 1);
983 rb_define_method(cPOSIX_MQ, "nonblock=", setnonblock, 1);
984 rb_define_method(cPOSIX_MQ, "notify_exec", setnotify_exec, 2);
985 rb_define_method(cPOSIX_MQ, "notify_cleanup", notify_cleanup, 0);
986 rb_define_method(cPOSIX_MQ, "nonblock?", getnonblock, 0);
987 #ifdef MQD_TO_FD
988 rb_define_method(cPOSIX_MQ, "to_io", to_io, 0);
989 #endif
991 id_new = rb_intern("new");
992 id_kill = rb_intern("kill");
993 id_fileno = rb_intern("fileno");
994 id_mul = rb_intern("*");
995 id_divmod = rb_intern("divmod");
996 id_flags = rb_intern("flags");
997 id_maxmsg = rb_intern("maxmsg");
998 id_msgsize = rb_intern("msgsize");
999 id_curmsgs = rb_intern("curmsgs");
1000 sym_r = ID2SYM(rb_intern("r"));
1001 sym_w = ID2SYM(rb_intern("w"));
1002 sym_rw = ID2SYM(rb_intern("rw"));