66f3f99b3e147905ddfd41caf96e05eb9d83d213
[ruby_posix_mq.git] / ext / posix_mq / posix_mq.c
blob66f3f99b3e147905ddfd41caf96e05eb9d83d213
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 # define PMQ_WANTARRAY (1<<0)
66 # define PMQ_TRY (1<<1)
68 static VALUE cAttr;
69 static ID id_new, id_kill, id_fileno, id_divmod;
70 static ID id_flags, id_maxmsg, id_msgsize, id_curmsgs;
71 static VALUE sym_r, sym_w, sym_rw;
72 static const mqd_t MQD_INVALID = (mqd_t)-1;
74 /* Ruby 1.8.6+ macros (for compatibility with Ruby 1.9) */
75 #ifndef RSTRING_PTR
76 # define RSTRING_PTR(s) (RSTRING(s)->ptr)
77 #endif
78 #ifndef RSTRING_LEN
79 # define RSTRING_LEN(s) (RSTRING(s)->len)
80 #endif
81 #ifndef RFLOAT_VALUE
82 # define RFLOAT_VALUE(f) (RFLOAT(f)->value)
83 #endif
85 #ifndef HAVE_RB_STR_SET_LEN
86 /* this is taken from Ruby 1.8.7, 1.8.6 may not have it */
87 # ifdef RUBINIUS
88 # error upgrade Rubinius, rb_str_set_len should be available
89 # endif
90 static void rb_18_str_set_len(VALUE str, long len)
92 RSTRING(str)->len = len;
93 RSTRING(str)->ptr[len] = '\0';
95 #define rb_str_set_len rb_18_str_set_len
96 #endif /* !defined(HAVE_RB_STR_SET_LEN) */
98 /* partial emulation of the 1.9 rb_thread_blocking_region under 1.8 */
99 #ifndef HAVE_RB_THREAD_BLOCKING_REGION
100 # include <rubysig.h>
101 # define RUBY_UBF_IO ((rb_unblock_function_t *)-1)
102 typedef void rb_unblock_function_t(void *);
103 typedef VALUE rb_blocking_function_t(void *);
104 static VALUE
105 rb_thread_blocking_region(
106 rb_blocking_function_t *func, void *data1,
107 rb_unblock_function_t *ubf, void *data2)
109 VALUE rv;
111 assert(RUBY_UBF_IO == ubf && "RUBY_UBF_IO required for emulation");
113 TRAP_BEG;
114 rv = func(data1);
115 TRAP_END;
117 return rv;
119 #endif /* ! HAVE_RB_THREAD_BLOCKING_REGION */
121 /* used to pass arguments to mq_open inside blocking region */
122 struct open_args {
123 int argc;
124 const char *name;
125 int oflags;
126 mode_t mode;
127 struct mq_attr attr;
130 /* used to pass arguments to mq_send/mq_receive inside blocking region */
131 struct rw_args {
132 mqd_t des;
133 char *msg_ptr;
134 size_t msg_len;
135 unsigned msg_prio;
136 struct timespec *timeout;
139 #ifndef HAVE_MQ_TIMEDSEND
140 static mqd_t
141 not_timedsend(mqd_t mqdes, const char *msg_ptr,
142 size_t msg_len, unsigned msg_prio,
143 const struct timespec *abs_timeout)
145 rb_bug("mq_timedsend workaround failed");
146 return (mqd_t)-1;
148 # define mq_timedsend not_timedsend
149 #endif
150 #ifndef HAVE_MQ_TIMEDRECEIVE
151 static ssize_t
152 not_timedreceive(mqd_t mqdes, char *msg_ptr,
153 size_t msg_len, unsigned *msg_prio,
154 const struct timespec *abs_timeout)
156 rb_bug("mq_timedreceive workaround failed");
157 return (mqd_t)-1;
159 # define mq_timedreceive not_timedreceive
160 #endif
162 #if defined(HAVE_MQ_TIMEDRECEIVE) && defined(HAVE_MQ_TIMEDSEND)
163 static void num2timespec(struct timespec *ts, VALUE t)
165 switch (TYPE(t)) {
166 case T_FIXNUM:
167 case T_BIGNUM:
168 ts->tv_sec = NUM2TIMET(t);
169 ts->tv_nsec = 0;
170 break;
171 case T_FLOAT: {
172 double f, d;
173 double val = RFLOAT_VALUE(t);
175 d = modf(val, &f);
176 if (d >= 0) {
177 ts->tv_nsec = (long)(d * 1e9 + 0.5);
178 } else {
179 ts->tv_nsec = (long)(-d * 1e9 + 0.5);
180 if (ts->tv_nsec > 0) {
181 ts->tv_nsec = 1000000000 - ts->tv_nsec;
182 f -= 1;
185 ts->tv_sec = (time_t)f;
186 if (f != ts->tv_sec)
187 rb_raise(rb_eRangeError, "%f out of range", val);
189 break;
190 default: {
191 VALUE f;
192 VALUE ary = rb_funcall(t, id_divmod, 1, INT2FIX(1));
194 Check_Type(ary, T_ARRAY);
196 ts->tv_sec = NUM2TIMET(rb_ary_entry(ary, 0));
197 f = rb_ary_entry(ary, 1);
198 f = rb_funcall(f, '*', 1, INT2FIX(1000000000));
199 ts->tv_nsec = NUM2LONG(f);
203 #else
204 static void num2timespec(struct timespec *ts, VALUE t)
206 rb_raise(rb_eNotImpError,
207 "mq_timedsend and/or mq_timedreceive missing");
209 #endif
211 static struct timespec *convert_timeout(struct timespec *dest, VALUE t)
213 struct timespec ts, now;
215 if (NIL_P(t))
216 return NULL;
218 num2timespec(&ts, t);
219 clock_gettime(CLOCK_REALTIME, &now);
220 dest->tv_sec = now.tv_sec + ts.tv_sec;
221 dest->tv_nsec = now.tv_nsec + ts.tv_nsec;
223 if (dest->tv_nsec > 1000000000) {
224 dest->tv_nsec -= 1000000000;
225 ++dest->tv_sec;
228 return dest;
231 /* (may) run without GVL */
232 static VALUE xopen(void *ptr)
234 struct open_args *x = ptr;
235 mqd_t rv;
237 switch (x->argc) {
238 case 2: rv = mq_open(x->name, x->oflags); break;
239 case 3: rv = mq_open(x->name, x->oflags, x->mode, NULL); break;
240 case 4: rv = mq_open(x->name, x->oflags, x->mode, &x->attr); break;
241 default: rv = MQD_INVALID;
244 return (VALUE)rv;
247 /* runs without GVL */
248 static VALUE xsend(void *ptr)
250 struct rw_args *x = ptr;
252 if (x->timeout)
253 return (VALUE)mq_timedsend(x->des, x->msg_ptr, x->msg_len,
254 x->msg_prio, x->timeout);
256 return (VALUE)mq_send(x->des, x->msg_ptr, x->msg_len, x->msg_prio);
259 /* runs without GVL */
260 static VALUE xrecv(void *ptr)
262 struct rw_args *x = ptr;
264 if (x->timeout)
265 return (VALUE)mq_timedreceive(x->des, x->msg_ptr, x->msg_len,
266 &x->msg_prio, x->timeout);
268 return (VALUE)mq_receive(x->des, x->msg_ptr, x->msg_len, &x->msg_prio);
271 /* called by GC */
272 static void mark(void *ptr)
274 struct posix_mq *mq = ptr;
276 rb_gc_mark(mq->name);
277 rb_gc_mark(mq->thread);
278 MQ_IO_MARK(mq);
281 /* called by GC */
282 static void _free(void *ptr)
284 struct posix_mq *mq = ptr;
286 if (mq->des != MQD_INVALID && MQ_IO_NIL_P(mq)) {
287 /* we ignore errors when gc-ing */
288 mq_close(mq->des);
289 errno = 0;
291 xfree(ptr);
294 /* automatically called at creation (before initialize) */
295 static VALUE alloc(VALUE klass)
297 struct posix_mq *mq;
298 VALUE rv = Data_Make_Struct(klass, struct posix_mq, mark, _free, mq);
300 mq->des = MQD_INVALID;
301 mq->attr.mq_flags = 0;
302 mq->attr.mq_maxmsg = 0;
303 mq->attr.mq_msgsize = -1;
304 mq->attr.mq_curmsgs = 0;
305 mq->name = Qnil;
306 mq->thread = Qnil;
307 MQ_IO_SET(mq, Qnil);
309 return rv;
312 /* unwraps the posix_mq struct from self */
313 static struct posix_mq *get(VALUE self, int need_valid)
315 struct posix_mq *mq;
317 Data_Get_Struct(self, struct posix_mq, mq);
319 if (need_valid && mq->des == MQD_INVALID)
320 rb_raise(rb_eIOError, "closed queue descriptor");
322 return mq;
325 static void check_struct_type(VALUE astruct)
327 if (CLASS_OF(astruct) == cAttr)
328 return;
329 astruct = rb_inspect(astruct);
330 rb_raise(rb_eTypeError, "not a POSIX_MQ::Attr: %s",
331 StringValuePtr(astruct));
334 static void rstruct2mqattr(struct mq_attr *attr, VALUE astruct, int all)
336 VALUE tmp;
338 check_struct_type(astruct);
339 attr->mq_flags = NUM2LONG(rb_funcall(astruct, id_flags, 0));
341 tmp = rb_funcall(astruct, id_maxmsg, 0);
342 if (all || !NIL_P(tmp))
343 attr->mq_maxmsg = NUM2LONG(tmp);
345 tmp = rb_funcall(astruct, id_msgsize, 0);
346 if (all || !NIL_P(tmp))
347 attr->mq_msgsize = NUM2LONG(tmp);
349 tmp = rb_funcall(astruct, id_curmsgs, 0);
350 if (!NIL_P(tmp))
351 attr->mq_curmsgs = NUM2LONG(tmp);
355 * call-seq:
356 * POSIX_MQ.new(name [, flags [, mode [, mq_attr]]) => mq
358 * Opens a POSIX message queue given by +name+. +name+ should start
359 * with a slash ("/") for portable applications.
361 * If a Symbol is given in place of integer +flags+, then:
363 * * +:r+ is equivalent to IO::RDONLY
364 * * +:w+ is equivalent to IO::CREAT|IO::WRONLY
365 * * +:rw+ is equivalent to IO::CREAT|IO::RDWR
367 * +mode+ is an integer and only used when IO::CREAT is used.
368 * +mq_attr+ is a POSIX_MQ::Attr and only used if IO::CREAT is used.
369 * If +mq_attr+ is not specified when creating a queue, then the
370 * system defaults will be used.
372 * See the manpage for mq_open(3) for more details on this function.
374 static VALUE init(int argc, VALUE *argv, VALUE self)
376 struct posix_mq *mq = get(self, 0);
377 struct open_args x;
378 VALUE name, oflags, mode, attr;
380 rb_scan_args(argc, argv, "13", &name, &oflags, &mode, &attr);
382 switch (TYPE(oflags)) {
383 case T_NIL:
384 x.oflags = O_RDONLY;
385 break;
386 case T_SYMBOL:
387 if (oflags == sym_r)
388 x.oflags = O_RDONLY;
389 else if (oflags == sym_w)
390 x.oflags = O_CREAT|O_WRONLY;
391 else if (oflags == sym_rw)
392 x.oflags = O_CREAT|O_RDWR;
393 else {
394 oflags = rb_inspect(oflags);
395 rb_raise(rb_eArgError,
396 "symbol must be :r, :w, or :rw: %s",
397 StringValuePtr(oflags));
399 break;
400 case T_BIGNUM:
401 case T_FIXNUM:
402 x.oflags = NUM2INT(oflags);
403 break;
404 default:
405 rb_raise(rb_eArgError, "flags must be an int, :r, :w, or :wr");
408 x.name = StringValueCStr(name);
409 x.argc = 2;
411 switch (TYPE(mode)) {
412 case T_FIXNUM:
413 x.argc = 3;
414 x.mode = NUM2UINT(mode);
415 break;
416 case T_NIL:
417 if (x.oflags & O_CREAT) {
418 x.argc = 3;
419 x.mode = 0666;
421 break;
422 default:
423 rb_raise(rb_eArgError, "mode not an integer");
426 switch (TYPE(attr)) {
427 case T_STRUCT:
428 x.argc = 4;
429 rstruct2mqattr(&x.attr, attr, 1);
431 /* principle of least surprise */
432 if (x.attr.mq_flags & O_NONBLOCK)
433 x.oflags |= O_NONBLOCK;
434 break;
435 case T_NIL:
436 break;
437 default:
438 check_struct_type(attr);
441 mq->des = (mqd_t)xopen(&x);
442 if (mq->des == MQD_INVALID) {
443 switch (errno) {
444 case ENOMEM:
445 case EMFILE:
446 case ENFILE:
447 case ENOSPC:
448 rb_gc();
449 mq->des = (mqd_t)xopen(&x);
451 if (mq->des == MQD_INVALID)
452 rb_sys_fail("mq_open");
455 mq->name = rb_str_dup(name);
456 if (x.oflags & O_NONBLOCK)
457 mq->attr.mq_flags = O_NONBLOCK;
459 return self;
463 * call-seq:
464 * POSIX_MQ.unlink(name) => 1
466 * Unlinks the message queue given by +name+. The queue will be destroyed
467 * when the last process with the queue open closes its queue descriptors.
469 static VALUE s_unlink(VALUE self, VALUE name)
471 mqd_t rv = mq_unlink(StringValueCStr(name));
473 if (rv == MQD_INVALID)
474 rb_sys_fail("mq_unlink");
476 return INT2NUM(1);
480 * call-seq:
481 * mq.unlink => mq
483 * Unlinks the message queue to prevent other processes from accessing it.
484 * All existing queue descriptors to this queue including those opened by
485 * other processes are unaffected. The queue will only be destroyed
486 * when the last process with open descriptors to this queue closes
487 * the descriptors.
489 static VALUE _unlink(VALUE self)
491 struct posix_mq *mq = get(self, 0);
492 mqd_t rv;
494 assert(TYPE(mq->name) == T_STRING && "mq->name is not a string");
496 rv = mq_unlink(RSTRING_PTR(mq->name));
497 if (rv == MQD_INVALID)
498 rb_sys_fail("mq_unlink");
500 return self;
503 static void setup_send_buffer(struct rw_args *x, VALUE buffer)
505 buffer = rb_obj_as_string(buffer);
506 x->msg_ptr = RSTRING_PTR(buffer);
507 x->msg_len = (size_t)RSTRING_LEN(buffer);
510 static VALUE _send(int sflags, int argc, VALUE *argv, VALUE self);
513 * call-seq:
514 * mq.send(string [,priority[, timeout]]) => true
516 * Inserts the given +string+ into the message queue with an optional,
517 * unsigned integer +priority+. If the optional +timeout+ is specified,
518 * then Errno::ETIMEDOUT will be raised if the operation cannot complete
519 * before +timeout+ seconds has elapsed. Without +timeout+, this method
520 * may block until the queue is writable.
522 * On some older systems, the +timeout+ argument is not currently
523 * supported and may raise NotImplementedError if +timeout+ is used.
525 static VALUE my_send(int argc, VALUE *argv, VALUE self)
527 return _send(0, argc, argv, self);
530 static VALUE _send(int sflags, int argc, VALUE *argv, VALUE self)
532 struct posix_mq *mq = get(self, 1);
533 struct rw_args x;
534 VALUE buffer, prio, timeout;
535 mqd_t rv;
536 struct timespec expire;
538 rb_scan_args(argc, argv, "12", &buffer, &prio, &timeout);
540 setup_send_buffer(&x, buffer);
541 x.des = mq->des;
542 x.timeout = convert_timeout(&expire, timeout);
543 x.msg_prio = NIL_P(prio) ? 0 : NUM2UINT(prio);
545 retry:
546 rv = (mqd_t)rb_thread_blocking_region(xsend, &x, RUBY_UBF_IO, 0);
547 if (rv == MQD_INVALID) {
548 if (errno == EINTR)
549 goto retry;
550 if (errno == EAGAIN && (sflags & PMQ_TRY))
551 return Qfalse;
552 rb_sys_fail("mq_send");
555 return Qtrue;
559 * call-seq:
560 * mq << string => mq
562 * Inserts the given +string+ into the message queue with a
563 * default priority of 0 and no timeout.
565 * Returns itself so its calls may be chained. This use is only
566 * recommended only for users who expect blocking behavior from
567 * the queue.
569 static VALUE send0(VALUE self, VALUE buffer)
571 struct posix_mq *mq = get(self, 1);
572 struct rw_args x;
573 mqd_t rv;
575 setup_send_buffer(&x, buffer);
576 x.des = mq->des;
577 x.timeout = NULL;
578 x.msg_prio = 0;
580 retry:
581 rv = (mqd_t)rb_thread_blocking_region(xsend, &x, RUBY_UBF_IO, 0);
582 if (rv == MQD_INVALID) {
583 if (errno == EINTR)
584 goto retry;
585 rb_sys_fail("mq_send");
588 return self;
591 #ifdef MQD_TO_FD
593 * call-seq:
594 * mq.to_io => IO
596 * Returns an IO.select-able +IO+ object. This method is only available
597 * under Linux and FreeBSD and is not intended to be portable.
599 static VALUE to_io(VALUE self)
601 struct posix_mq *mq = get(self, 1);
602 int fd = MQD_TO_FD(mq->des);
604 if (NIL_P(mq->io))
605 mq->io = rb_funcall(rb_cIO, id_new, 1, INT2NUM(fd));
607 return mq->io;
609 #endif
611 static VALUE _receive(int rflags, int argc, VALUE *argv, VALUE self);
614 * call-seq:
615 * mq.receive([buffer, [timeout]]) => [ message, priority ]
617 * Takes the highest priority message off the queue and returns
618 * an array containing the message as a String and the Integer
619 * priority of the message.
621 * If the optional +buffer+ is present, then it must be a String
622 * which will receive the data.
624 * If the optional +timeout+ is present, then it may be a Float
625 * or Integer specifying the timeout in seconds. Errno::ETIMEDOUT
626 * will be raised if +timeout+ has elapsed and there are no messages
627 * in the queue.
629 * On some older systems, the +timeout+ argument is not currently
630 * supported and may raise NotImplementedError if +timeout+ is used.
632 static VALUE receive(int argc, VALUE *argv, VALUE self)
634 return _receive(PMQ_WANTARRAY, argc, argv, self);
638 * call-seq:
639 * mq.shift([buffer, [timeout]]) => message
641 * Takes the highest priority message off the queue and returns
642 * the message as a String.
644 * If the optional +buffer+ is present, then it must be a String
645 * which will receive the data.
647 * If the optional +timeout+ is present, then it may be a Float
648 * or Integer specifying the timeout in seconds. Errno::ETIMEDOUT
649 * will be raised if +timeout+ has elapsed and there are no messages
650 * in the queue.
652 * On some older systems, the +timeout+ argument is not currently
653 * supported and may raise NotImplementedError if +timeout+ is used.
655 static VALUE shift(int argc, VALUE *argv, VALUE self)
657 return _receive(0, argc, argv, self);
660 static VALUE _receive(int rflags, int argc, VALUE *argv, VALUE self)
662 struct posix_mq *mq = get(self, 1);
663 struct rw_args x;
664 VALUE buffer, timeout;
665 ssize_t r;
666 struct timespec expire;
668 if (mq->attr.mq_msgsize < 0) {
669 if (mq_getattr(mq->des, &mq->attr) < 0)
670 rb_sys_fail("mq_getattr");
673 rb_scan_args(argc, argv, "02", &buffer, &timeout);
674 x.timeout = convert_timeout(&expire, timeout);
676 if (NIL_P(buffer)) {
677 buffer = rb_str_new(0, mq->attr.mq_msgsize);
678 } else {
679 StringValue(buffer);
680 rb_str_modify(buffer);
681 rb_str_resize(buffer, mq->attr.mq_msgsize);
683 OBJ_TAINT(buffer);
684 x.msg_ptr = RSTRING_PTR(buffer);
685 x.msg_len = (size_t)mq->attr.mq_msgsize;
686 x.des = mq->des;
688 retry:
689 r = (ssize_t)rb_thread_blocking_region(xrecv, &x, RUBY_UBF_IO, 0);
690 if (r < 0) {
691 if (errno == EINTR)
692 goto retry;
693 if (errno == EAGAIN && (rflags & PMQ_TRY))
694 return Qnil;
695 rb_sys_fail("mq_receive");
698 rb_str_set_len(buffer, r);
700 if (rflags & PMQ_WANTARRAY)
701 return rb_ary_new3(2, buffer, UINT2NUM(x.msg_prio));
702 return buffer;
706 * call-seq:
707 * mq.attr => mq_attr
709 * Returns a POSIX_MQ::Attr struct containing the attributes
710 * of the message queue. See the mq_getattr(3) manpage for
711 * more details.
713 static VALUE getattr(VALUE self)
715 struct posix_mq *mq = get(self, 1);
717 if (mq_getattr(mq->des, &mq->attr) < 0)
718 rb_sys_fail("mq_getattr");
720 return rb_funcall(cAttr, id_new, 4,
721 LONG2NUM(mq->attr.mq_flags),
722 LONG2NUM(mq->attr.mq_maxmsg),
723 LONG2NUM(mq->attr.mq_msgsize),
724 LONG2NUM(mq->attr.mq_curmsgs));
728 * call-seq:
729 * mq.attr = POSIX_MQ::Attr(IO::NONBLOCK) => mq_attr
731 * Only the IO::NONBLOCK flag may be set or unset (zero) in this manner.
732 * See the mq_setattr(3) manpage for more details.
734 * Consider using the POSIX_MQ#nonblock= method as it is easier and
735 * more natural to use.
737 static VALUE setattr(VALUE self, VALUE astruct)
739 struct posix_mq *mq = get(self, 1);
740 struct mq_attr newattr;
742 rstruct2mqattr(&newattr, astruct, 0);
744 if (mq_setattr(mq->des, &newattr, NULL) < 0)
745 rb_sys_fail("mq_setattr");
747 return astruct;
751 * call-seq:
752 * mq.close => nil
754 * Closes the underlying message queue descriptor.
755 * If this descriptor had a registered notification request, the request
756 * will be removed so another descriptor or process may register a
757 * notification request. Message queue descriptors are automatically
758 * closed by garbage collection.
760 static VALUE _close(VALUE self)
762 struct posix_mq *mq = get(self, 1);
764 if (! MQ_IO_CLOSE(mq)) {
765 if (mq_close(mq->des) == -1)
766 rb_sys_fail("mq_close");
768 mq->des = MQD_INVALID;
770 return Qnil;
774 * call-seq:
775 * mq.closed? => true or false
777 * Returns +true+ if the message queue descriptor is closed and therefore
778 * unusable, otherwise +false+
780 static VALUE closed(VALUE self)
782 struct posix_mq *mq = get(self, 0);
784 return mq->des == MQD_INVALID ? Qtrue : Qfalse;
788 * call-seq:
789 * mq.name => string
791 * Returns the string name of message queue associated with +mq+
793 static VALUE name(VALUE self)
795 struct posix_mq *mq = get(self, 0);
797 return rb_str_dup(mq->name);
800 static int lookup_sig(VALUE sig)
802 static VALUE list;
803 const char *ptr;
804 long len;
806 sig = rb_obj_as_string(sig);
807 len = RSTRING_LEN(sig);
808 ptr = RSTRING_PTR(sig);
810 if (len > 3 && !memcmp("SIG", ptr, 3))
811 sig = rb_str_new(ptr + 3, len - 3);
813 if (!list) {
814 VALUE mSignal = rb_const_get(rb_cObject, rb_intern("Signal"));
816 list = rb_funcall(mSignal, rb_intern("list"), 0, 0);
817 rb_global_variable(&list);
820 sig = rb_hash_aref(list, sig);
821 if (NIL_P(sig))
822 rb_raise(rb_eArgError, "invalid signal: %s\n", ptr);
824 return NUM2INT(sig);
828 * TODO: Under Linux, we could just use netlink directly
829 * the same way glibc does...
831 /* we spawn a thread just to write ONE byte into an fd (usually a pipe) */
832 static void thread_notify_fd(union sigval sv)
834 int fd = sv.sival_int;
836 while ((write(fd, "", 1) < 0) && (errno == EINTR || errno == EAGAIN));
839 static void my_mq_notify(mqd_t des, struct sigevent *not)
841 mqd_t rv = mq_notify(des, not);
843 if (rv == MQD_INVALID) {
844 if (errno == ENOMEM) {
845 rb_gc();
846 rv = mq_notify(des, not);
848 if (rv == MQD_INVALID)
849 rb_sys_fail("mq_notify");
853 static void lower_stack_size(pthread_attr_t *attr)
855 /* some OSes have ridiculously small stack sizes */
856 #ifdef PTHREAD_STACK_MIN
857 size_t stack_size = PTHREAD_STACK_MIN;
858 size_t min_size = 4096;
860 if (stack_size < min_size)
861 stack_size = min_size;
862 pthread_attr_setstacksize(attr, stack_size);
863 #endif
866 /* :nodoc: */
867 static VALUE setnotify_exec(VALUE self, VALUE io, VALUE thr)
869 int fd = NUM2INT(rb_funcall(io, id_fileno, 0, 0));
870 struct posix_mq *mq = get(self, 1);
871 struct sigevent not;
872 pthread_attr_t attr;
874 errno = pthread_attr_init(&attr);
875 if (errno) rb_sys_fail("pthread_attr_init");
877 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
878 if (errno) rb_sys_fail("pthread_attr_setdetachstate");
880 lower_stack_size(&attr);
881 not.sigev_notify = SIGEV_THREAD;
882 not.sigev_notify_function = thread_notify_fd;
883 not.sigev_notify_attributes = &attr;
884 not.sigev_value.sival_int = fd;
886 if (!NIL_P(mq->thread))
887 rb_funcall(mq->thread, id_kill, 0, 0);
888 mq->thread = thr;
890 my_mq_notify(mq->des, &not);
892 return thr;
895 /* :nodoc: */
896 static VALUE notify_cleanup(VALUE self)
898 struct posix_mq *mq = get(self, 1);
900 if (!NIL_P(mq->thread)) {
901 rb_funcall(mq->thread, id_kill, 0, 0);
902 mq->thread = Qnil;
904 return Qnil;
908 * call-seq:
909 * mq.notify = signal => signal
911 * Registers the notification request to deliver a given +signal+
912 * to the current process when message is received.
913 * If +signal+ is +nil+, it will unregister and disable the notification
914 * request to allow other processes to register a request.
915 * If +signal+ is +false+, it will register a no-op notification request
916 * which will prevent other processes from registering a notification.
917 * If +signal+ is an +IO+ object, it will spawn a thread upon the
918 * arrival of the next message and write one "\\0" byte to the file
919 * descriptor belonging to that IO object.
920 * Only one process may have a notification request for a queue
921 * at a time, Errno::EBUSY will be raised if there is already
922 * a notification request registration for the queue.
924 * Notifications are only fired once and processes must reregister
925 * for subsequent notifications.
927 * For readers of the mq_notify(3) manpage, passing +false+
928 * is equivalent to SIGEV_NONE, and passing +nil+ is equivalent
929 * of passing a NULL notification pointer to mq_notify(3).
931 static VALUE setnotify(VALUE self, VALUE arg)
933 struct posix_mq *mq = get(self, 1);
934 struct sigevent not;
935 struct sigevent * notification = &not;
936 VALUE rv = arg;
938 notify_cleanup(self);
939 not.sigev_notify = SIGEV_SIGNAL;
941 switch (TYPE(arg)) {
942 case T_FALSE:
943 not.sigev_notify = SIGEV_NONE;
944 break;
945 case T_NIL:
946 notification = NULL;
947 break;
948 case T_FIXNUM:
949 not.sigev_signo = NUM2INT(arg);
950 break;
951 case T_SYMBOL:
952 case T_STRING:
953 not.sigev_signo = lookup_sig(arg);
954 rv = INT2NUM(not.sigev_signo);
955 break;
956 default:
957 rb_raise(rb_eArgError, "must be a signal or nil");
960 my_mq_notify(mq->des, notification);
962 return rv;
966 * call-seq:
967 * mq.nonblock? => true or false
969 * Returns the current non-blocking state of the message queue descriptor.
971 static VALUE nonblock_p(VALUE self)
973 struct posix_mq *mq = get(self, 1);
975 if (mq_getattr(mq->des, &mq->attr) < 0)
976 rb_sys_fail("mq_getattr");
977 return mq->attr.mq_flags & O_NONBLOCK ? Qtrue : Qfalse;
981 * call-seq:
982 * mq.nonblock = boolean => boolean
984 * Enables or disables non-blocking operation for the message queue
985 * descriptor. Errno::EAGAIN will be raised in situations where
986 * the queue would block. This is not compatible with +timeout+
987 * arguments to POSIX_MQ#send and POSIX_MQ#receive.
989 static VALUE setnonblock(VALUE self, VALUE nb)
991 struct mq_attr newattr;
992 struct posix_mq *mq = get(self, 1);
994 if (nb == Qtrue)
995 newattr.mq_flags = O_NONBLOCK;
996 else if (nb == Qfalse)
997 newattr.mq_flags = 0;
998 else
999 rb_raise(rb_eArgError, "must be true or false");
1001 if (mq_setattr(mq->des, &newattr, &mq->attr) < 0)
1002 rb_sys_fail("mq_setattr");
1004 mq->attr.mq_flags = newattr.mq_flags;
1006 return nb;
1010 * call-seq:
1011 * mq.trysend(string [,priority[, timeout]]) => +true+ or +false+
1013 * Exactly like POSIX_MQ#send, except it returns +false+ instead of raising
1014 * Errno::EAGAIN when non-blocking operation is desired and returns +true+
1015 * on success instead of +nil+.
1017 * This does not guarantee non-blocking behavior, the message queue must
1018 * be made non-blocking before calling this method.
1020 static VALUE trysend(int argc, VALUE *argv, VALUE self)
1022 return _send(PMQ_TRY, argc, argv, self);
1026 * call-seq:
1027 * mq.tryshift([buffer [, timeout]]) => message or nil
1029 * Exactly like POSIX_MQ#shift, except it returns +nil+ instead of raising
1030 * Errno::EAGAIN when non-blocking operation is desired.
1032 * This does not guarantee non-blocking behavior, the message queue must
1033 * be made non-blocking before calling this method.
1035 static VALUE tryshift(int argc, VALUE *argv, VALUE self)
1037 return _receive(PMQ_TRY, argc, argv, self);
1041 * call-seq:
1042 * mq.tryreceive([buffer [, timeout]]) => [ message, priority ] or nil
1044 * Exactly like POSIX_MQ#receive, except it returns +nil+ instead of raising
1045 * Errno::EAGAIN when non-blocking operation is desired.
1047 * This does not guarantee non-blocking behavior, the message queue must
1048 * be made non-blocking before calling this method.
1050 static VALUE tryreceive(int argc, VALUE *argv, VALUE self)
1052 return _receive(PMQ_WANTARRAY|PMQ_TRY, argc, argv, self);
1055 void Init_posix_mq_ext(void)
1057 VALUE cPOSIX_MQ = rb_define_class("POSIX_MQ", rb_cObject);
1058 rb_define_alloc_func(cPOSIX_MQ, alloc);
1059 cAttr = rb_const_get(cPOSIX_MQ, rb_intern("Attr"));
1062 * The maximum number of open message descriptors supported
1063 * by the system. This may be -1, in which case it is dynamically
1064 * set at runtime. Consult your operating system documentation
1065 * for system-specific information about this.
1067 rb_define_const(cPOSIX_MQ, "OPEN_MAX",
1068 LONG2NUM(sysconf(_SC_MQ_OPEN_MAX)));
1071 * The maximum priority that may be specified for POSIX_MQ#send
1072 * On POSIX-compliant systems, this is at least 31, but some
1073 * systems allow higher limits.
1074 * The minimum priority is always zero.
1076 rb_define_const(cPOSIX_MQ, "PRIO_MAX",
1077 LONG2NUM(sysconf(_SC_MQ_PRIO_MAX)));
1079 rb_define_singleton_method(cPOSIX_MQ, "unlink", s_unlink, 1);
1081 rb_define_private_method(cPOSIX_MQ, "initialize", init, -1);
1082 rb_define_method(cPOSIX_MQ, "send", my_send, -1);
1083 rb_define_method(cPOSIX_MQ, "<<", send0, 1);
1084 rb_define_method(cPOSIX_MQ, "trysend", trysend, -1);
1085 rb_define_method(cPOSIX_MQ, "receive", receive, -1);
1086 rb_define_method(cPOSIX_MQ, "tryreceive", tryreceive, -1);
1087 rb_define_method(cPOSIX_MQ, "shift", shift, -1);
1088 rb_define_method(cPOSIX_MQ, "tryshift", tryshift, -1);
1089 rb_define_method(cPOSIX_MQ, "attr", getattr, 0);
1090 rb_define_method(cPOSIX_MQ, "attr=", setattr, 1);
1091 rb_define_method(cPOSIX_MQ, "close", _close, 0);
1092 rb_define_method(cPOSIX_MQ, "closed?", closed, 0);
1093 rb_define_method(cPOSIX_MQ, "unlink", _unlink, 0);
1094 rb_define_method(cPOSIX_MQ, "name", name, 0);
1095 rb_define_method(cPOSIX_MQ, "notify=", setnotify, 1);
1096 rb_define_method(cPOSIX_MQ, "nonblock=", setnonblock, 1);
1097 rb_define_private_method(cPOSIX_MQ, "notify_exec", setnotify_exec, 2);
1098 rb_define_private_method(cPOSIX_MQ, "notify_cleanup", notify_cleanup, 0);
1099 rb_define_method(cPOSIX_MQ, "nonblock?", nonblock_p, 0);
1100 #ifdef MQD_TO_FD
1101 rb_define_method(cPOSIX_MQ, "to_io", to_io, 0);
1102 #endif
1104 id_new = rb_intern("new");
1105 id_kill = rb_intern("kill");
1106 id_fileno = rb_intern("fileno");
1107 id_divmod = rb_intern("divmod");
1108 id_flags = rb_intern("flags");
1109 id_maxmsg = rb_intern("maxmsg");
1110 id_msgsize = rb_intern("msgsize");
1111 id_curmsgs = rb_intern("curmsgs");
1112 sym_r = ID2SYM(rb_intern("r"));
1113 sym_w = ID2SYM(rb_intern("w"));
1114 sym_rw = ID2SYM(rb_intern("rw"));