do not release GVL when unlinking/opening
[ruby_posix_mq.git] / ext / posix_mq / posix_mq.c
blob5b7a3ed25069ae5f9e0e5bb01bd226745c4829a8
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 #include <time.h>
14 #include <mqueue.h>
15 #include <fcntl.h>
16 #include <sys/stat.h>
17 #include <errno.h>
18 #include <assert.h>
19 #include <unistd.h>
21 #if defined(__linux__)
22 # define MQD_TO_FD(mqd) (int)(mqd)
23 #elif defined(HAVE___MQ_OSHANDLE) /* FreeBSD */
24 # define MQD_TO_FD(mqd) __mq_oshandle(mqd)
25 #else
26 # warning mqd_t is not select()-able on your OS
27 # define MQ_IO_MARK(mq) ((void)(0))
28 # define MQ_IO_SET(mq,val) ((void)(0))
29 #endif
31 #ifdef MQD_TO_FD
32 # define MQ_IO_MARK(mq) rb_gc_mark((mq)->io)
33 # define MQ_IO_SET(mq,val) do { (mq)->io = (val); } while (0)
34 #endif
36 struct posix_mq {
37 mqd_t des;
38 struct mq_attr attr;
39 VALUE name;
40 VALUE thread;
41 #ifdef MQD_TO_FD
42 VALUE io;
43 #endif
46 static VALUE cPOSIX_MQ, cAttr;
47 static ID id_new, id_kill, id_fileno;
48 static ID sym_r, sym_w, sym_rw;
49 static const mqd_t MQD_INVALID = (mqd_t)-1;
51 /* Ruby 1.8.6+ macros (for compatibility with Ruby 1.9) */
52 #ifndef RSTRING_PTR
53 # define RSTRING_PTR(s) (RSTRING(s)->ptr)
54 #endif
55 #ifndef RSTRING_LEN
56 # define RSTRING_LEN(s) (RSTRING(s)->len)
57 #endif
58 #ifndef RSTRUCT_PTR
59 # define RSTRUCT_PTR(s) (RSTRUCT(s)->ptr)
60 #endif
61 #ifndef RSTRUCT_LEN
62 # define RSTRUCT_LEN(s) (RSTRUCT(s)->len)
63 #endif
65 #ifndef HAVE_RB_STR_SET_LEN
66 # ifdef RUBINIUS
67 # define rb_str_set_len(str,len) rb_str_resize(str,len)
68 # else /* 1.8.6 optimized version */
69 /* this is taken from Ruby 1.8.7, 1.8.6 may not have it */
70 static void rb_18_str_set_len(VALUE str, long len)
72 RSTRING(str)->len = len;
73 RSTRING(str)->ptr[len] = '\0';
75 # define rb_str_set_len(str,len) rb_18_str_set_len(str,len)
76 # endif /* ! RUBINIUS */
77 #endif /* !defined(HAVE_RB_STR_SET_LEN) */
79 #ifndef HAVE_RB_STRUCT_ALLOC_NOINIT
80 static VALUE rb_struct_alloc_noinit(VALUE class)
82 return rb_funcall(class, id_new, 0, 0);
84 #endif /* !defined(HAVE_RB_STRUCT_ALLOC_NOINIT) */
86 /* partial emulation of the 1.9 rb_thread_blocking_region under 1.8 */
87 #ifndef HAVE_RB_THREAD_BLOCKING_REGION
88 # include <rubysig.h>
89 # define RUBY_UBF_IO ((rb_unblock_function_t *)-1)
90 typedef void rb_unblock_function_t(void *);
91 typedef VALUE rb_blocking_function_t(void *);
92 static VALUE
93 rb_thread_blocking_region(
94 rb_blocking_function_t *func, void *data1,
95 rb_unblock_function_t *ubf, void *data2)
97 VALUE rv;
99 assert(RUBY_UBF_IO == ubf && "RUBY_UBF_IO required for emulation");
101 TRAP_BEG;
102 rv = func(data1);
103 TRAP_END;
105 return rv;
107 #endif /* ! HAVE_RB_THREAD_BLOCKING_REGION */
109 /* used to pass arguments to mq_open inside blocking region */
110 struct open_args {
111 int argc;
112 const char *name;
113 int oflags;
114 mode_t mode;
115 struct mq_attr attr;
118 /* used to pass arguments to mq_send/mq_receive inside blocking region */
119 struct rw_args {
120 mqd_t des;
121 char *msg_ptr;
122 size_t msg_len;
123 unsigned msg_prio;
124 struct timespec *timeout;
127 /* hope it's there..., TODO: a better version that works in rbx */
128 struct timeval rb_time_interval(VALUE);
130 static struct timespec *convert_timeout(struct timespec *dest, VALUE time)
132 struct timeval tv, now;
134 if (NIL_P(time))
135 return NULL;
137 tv = rb_time_interval(time); /* aggregate return :( */
138 gettimeofday(&now, NULL);
139 dest->tv_sec = now.tv_sec + tv.tv_sec;
140 dest->tv_nsec = (now.tv_usec + tv.tv_usec) * 1000;
142 if (dest->tv_nsec > 1000000000) {
143 dest->tv_nsec -= 1000000000;
144 dest->tv_sec++;
147 return dest;
150 /* (may) run without GVL */
151 static VALUE xopen(void *ptr)
153 struct open_args *x = ptr;
154 mqd_t rv;
156 switch (x->argc) {
157 case 2: rv = mq_open(x->name, x->oflags); break;
158 case 3: rv = mq_open(x->name, x->oflags, x->mode, NULL); break;
159 case 4: rv = mq_open(x->name, x->oflags, x->mode, &x->attr); break;
160 default: rv = MQD_INVALID;
163 return (VALUE)rv;
166 /* runs without GVL */
167 static VALUE xsend(void *ptr)
169 struct rw_args *x = ptr;
171 if (x->timeout)
172 return (VALUE)mq_timedsend(x->des, x->msg_ptr, x->msg_len,
173 x->msg_prio, x->timeout);
175 return (VALUE)mq_send(x->des, x->msg_ptr, x->msg_len, x->msg_prio);
178 /* runs without GVL */
179 static VALUE xrecv(void *ptr)
181 struct rw_args *x = ptr;
183 if (x->timeout)
184 return (VALUE)mq_timedreceive(x->des, x->msg_ptr, x->msg_len,
185 &x->msg_prio, x->timeout);
187 return (VALUE)mq_receive(x->des, x->msg_ptr, x->msg_len, &x->msg_prio);
190 /* called by GC */
191 static void mark(void *ptr)
193 struct posix_mq *mq = ptr;
195 rb_gc_mark(mq->name);
196 rb_gc_mark(mq->thread);
197 MQ_IO_MARK(mq);
200 /* called by GC */
201 static void _free(void *ptr)
203 struct posix_mq *mq = ptr;
205 if (mq->des != MQD_INVALID) {
206 /* we ignore errors when gc-ing */
207 int saved_errno = errno;
209 mq_close(mq->des);
210 errno = saved_errno;
212 xfree(ptr);
215 /* automatically called at creation (before initialize) */
216 static VALUE alloc(VALUE klass)
218 struct posix_mq *mq;
219 VALUE rv = Data_Make_Struct(klass, struct posix_mq, mark, _free, mq);
221 mq->des = MQD_INVALID;
222 mq->attr.mq_flags = 0;
223 mq->attr.mq_maxmsg = 0;
224 mq->attr.mq_msgsize = -1;
225 mq->attr.mq_curmsgs = 0;
226 mq->name = Qnil;
227 mq->thread = Qnil;
228 MQ_IO_SET(mq, Qnil);
230 return rv;
233 /* unwraps the posix_mq struct from self */
234 static struct posix_mq *get(VALUE self, int need_valid)
236 struct posix_mq *mq;
238 Data_Get_Struct(self, struct posix_mq, mq);
240 if (need_valid && mq->des == MQD_INVALID)
241 rb_raise(rb_eIOError, "closed queue descriptor");
243 return mq;
246 /* converts the POSIX_MQ::Attr astruct into a struct mq_attr attr */
247 static void attr_from_struct(struct mq_attr *attr, VALUE astruct, int all)
249 VALUE *ptr;
251 if (CLASS_OF(astruct) != cAttr)
252 rb_raise(rb_eArgError, "not a POSIX_MQ::Attr: %s",
253 RSTRING_PTR(rb_inspect(astruct)));
255 ptr = RSTRUCT_PTR(astruct);
257 attr->mq_flags = NUM2LONG(ptr[0]);
259 if (all || !NIL_P(ptr[1]))
260 attr->mq_maxmsg = NUM2LONG(ptr[1]);
261 if (all || !NIL_P(ptr[2]))
262 attr->mq_msgsize = NUM2LONG(ptr[2]);
263 if (!NIL_P(ptr[3]))
264 attr->mq_curmsgs = NUM2LONG(ptr[3]);
268 * call-seq:
269 * POSIX_MQ.new(name [, flags [, mode [, mq_attr]]) => mq
271 * Opens a POSIX message queue given by +name+. +name+ should start
272 * with a slash ("/") for portable applications.
274 * If a Symbol is given in place of integer +flags+, then:
276 * * +:r+ is equivalent to IO::RDONLY
277 * * +:w+ is equivalent to IO::CREAT|IO::WRONLY
278 * * +:rw+ is equivalent to IO::CREAT|IO::RDWR
280 * +mode+ is an integer and only used when IO::CREAT is used.
281 * +mq_attr+ is a POSIX_MQ::Attr and only used if IO::CREAT is used.
282 * If +mq_attr+ is not specified when creating a queue, then the
283 * system defaults will be used.
285 * See the manpage for mq_open(3) for more details on this function.
287 static VALUE init(int argc, VALUE *argv, VALUE self)
289 struct posix_mq *mq = get(self, 0);
290 struct open_args x;
291 VALUE name, oflags, mode, attr;
293 rb_scan_args(argc, argv, "13", &name, &oflags, &mode, &attr);
295 if (TYPE(name) != T_STRING)
296 rb_raise(rb_eArgError, "name must be a string");
298 switch (TYPE(oflags)) {
299 case T_NIL:
300 x.oflags = O_RDONLY;
301 break;
302 case T_SYMBOL:
303 if (oflags == sym_r)
304 x.oflags = O_RDONLY;
305 else if (oflags == sym_w)
306 x.oflags = O_CREAT|O_WRONLY;
307 else if (oflags == sym_rw)
308 x.oflags = O_CREAT|O_RDWR;
309 else
310 rb_raise(rb_eArgError,
311 "symbol must be :r, :w, or :rw: %s",
312 RSTRING_PTR(rb_inspect(oflags)));
313 break;
314 case T_BIGNUM:
315 case T_FIXNUM:
316 x.oflags = NUM2INT(oflags);
317 break;
318 default:
319 rb_raise(rb_eArgError, "flags must be an int, :r, :w, or :wr");
322 x.name = RSTRING_PTR(name);
323 x.argc = 2;
325 switch (TYPE(mode)) {
326 case T_FIXNUM:
327 x.argc = 3;
328 x.mode = NUM2UINT(mode);
329 break;
330 case T_NIL:
331 if (x.oflags & O_CREAT) {
332 x.argc = 3;
333 x.mode = 0666;
335 break;
336 default:
337 rb_raise(rb_eArgError, "mode not an integer");
340 switch (TYPE(attr)) {
341 case T_STRUCT:
342 x.argc = 4;
343 attr_from_struct(&x.attr, attr, 1);
345 /* principle of least surprise */
346 if (x.attr.mq_flags & O_NONBLOCK)
347 x.oflags |= O_NONBLOCK;
348 break;
349 case T_NIL:
350 break;
351 default:
352 rb_raise(rb_eArgError, "attr must be a POSIX_MQ::Attr: %s",
353 RSTRING_PTR(rb_inspect(attr)));
356 mq->des = (mqd_t)xopen(&x);
357 if (mq->des == MQD_INVALID)
358 rb_sys_fail("mq_open");
360 mq->name = rb_str_dup(name);
361 if (x.oflags & O_NONBLOCK)
362 mq->attr.mq_flags = O_NONBLOCK;
364 return self;
368 * call-seq:
369 * POSIX_MQ.unlink(name) => 1
371 * Unlinks the message queue given by +name+. The queue will be destroyed
372 * when the last process with the queue open closes its queue descriptors.
374 static VALUE s_unlink(VALUE self, VALUE name)
376 mqd_t rv;
378 if (TYPE(name) != T_STRING)
379 rb_raise(rb_eArgError, "argument must be a string");
381 rv = mq_unlink(RSTRING_PTR(name));
382 if (rv == MQD_INVALID)
383 rb_sys_fail("mq_unlink");
385 return INT2NUM(1);
389 * call-seq:
390 * mq.unlink => mq
392 * Unlinks the message queue to prevent other processes from accessing it.
393 * All existing queue descriptors to this queue including those opened by
394 * other processes are unaffected. The queue will only be destroyed
395 * when the last process with open descriptors to this queue closes
396 * the descriptors.
398 static VALUE _unlink(VALUE self)
400 struct posix_mq *mq = get(self, 0);
401 mqd_t rv;
403 assert(TYPE(mq->name) == T_STRING && "mq->name is not a string");
405 rv = mq_unlink(RSTRING_PTR(mq->name));
406 if (rv == MQD_INVALID)
407 rb_sys_fail("mq_unlink");
409 return self;
412 static void setup_send_buffer(struct rw_args *x, VALUE buffer)
414 buffer = rb_obj_as_string(buffer);
415 x->msg_ptr = RSTRING_PTR(buffer);
416 x->msg_len = (size_t)RSTRING_LEN(buffer);
420 * call-seq:
421 * mq.send(string [,priority[, timeout]]) => nil
423 * Inserts the given +string+ into the message queue with an optional,
424 * unsigned integer +priority+. If the optional +timeout+ is specified,
425 * then Errno::ETIMEDOUT will be raised if the operation cannot complete
426 * before +timeout+ seconds has elapsed. Without +timeout+, this method
427 * may block until the queue is writable.
429 static VALUE _send(int argc, VALUE *argv, VALUE self)
431 struct posix_mq *mq = get(self, 1);
432 struct rw_args x;
433 VALUE buffer, prio, timeout;
434 mqd_t rv;
435 struct timespec expire;
437 rb_scan_args(argc, argv, "12", &buffer, &prio, &timeout);
439 setup_send_buffer(&x, buffer);
440 x.des = mq->des;
441 x.timeout = convert_timeout(&expire, timeout);
442 x.msg_prio = NIL_P(prio) ? 0 : NUM2UINT(prio);
444 if (mq->attr.mq_flags & O_NONBLOCK)
445 rv = (mqd_t)xsend(&x);
446 else
447 rv = (mqd_t)rb_thread_blocking_region(xsend, &x,
448 RUBY_UBF_IO, 0);
449 if (rv == MQD_INVALID)
450 rb_sys_fail("mq_send");
452 return Qnil;
456 * call-seq:
457 * mq << string => mq
459 * Inserts the given +string+ into the message queue with a
460 * default priority of 0 and no timeout.
462 static VALUE send0(VALUE self, VALUE buffer)
464 struct posix_mq *mq = get(self, 1);
465 struct rw_args x;
466 mqd_t rv;
468 setup_send_buffer(&x, buffer);
469 x.des = mq->des;
470 x.timeout = NULL;
471 x.msg_prio = 0;
473 rv = (mqd_t)rb_thread_blocking_region(xsend, &x, RUBY_UBF_IO, 0);
474 if (rv == MQD_INVALID)
475 rb_sys_fail("mq_send");
477 return self;
480 #ifdef MQD_TO_FD
482 * call-seq:
483 * mq.to_io => IO
485 * Returns an IO.select-able +IO+ object. This method is only available
486 * under Linux and is not intended to be portable.
488 static VALUE to_io(VALUE self)
490 struct posix_mq *mq = get(self, 1);
491 int fd = MQD_TO_FD(mq->des);
493 if (NIL_P(mq->io))
494 mq->io = rb_funcall(rb_cIO, id_new, 1, INT2NUM(fd));
496 return mq->io;
498 #endif
500 static VALUE _receive(int wantarray, int argc, VALUE *argv, VALUE self);
503 * call-seq:
504 * mq.receive([buffer, [timeout]]) => [ message, priority ]
506 * Takes the highest priority message off the queue and returns
507 * an array containing the message as a String and the Integer
508 * priority of the message.
510 * If the optional +buffer+ is present, then it must be a String
511 * which will receive the data.
513 * If the optional +timeout+ is present, then it may be a Float
514 * or Integer specifying the timeout in seconds. Errno::ETIMEDOUT
515 * will be raised if +timeout+ has elapsed and there are no messages
516 * in the queue.
518 static VALUE receive(int argc, VALUE *argv, VALUE self)
520 return _receive(1, argc, argv, self);
524 * call-seq:
525 * mq.shift([buffer, [timeout]]) => message
527 * Takes the highest priority message off the queue and returns
528 * the message as a String.
530 * If the optional +buffer+ is present, then it must be a String
531 * which will receive the data.
533 * If the optional +timeout+ is present, then it may be a Float
534 * or Integer specifying the timeout in seconds. Errno::ETIMEDOUT
535 * will be raised if +timeout+ has elapsed and there are no messages
536 * in the queue.
538 static VALUE shift(int argc, VALUE *argv, VALUE self)
540 return _receive(0, argc, argv, self);
543 static VALUE _receive(int wantarray, int argc, VALUE *argv, VALUE self)
545 struct posix_mq *mq = get(self, 1);
546 struct rw_args x;
547 VALUE buffer, timeout;
548 ssize_t r;
549 struct timespec expire;
551 if (mq->attr.mq_msgsize < 0) {
552 if (mq_getattr(mq->des, &mq->attr) < 0)
553 rb_sys_fail("mq_getattr");
556 rb_scan_args(argc, argv, "02", &buffer, &timeout);
557 x.timeout = convert_timeout(&expire, timeout);
559 if (NIL_P(buffer)) {
560 buffer = rb_str_new(0, mq->attr.mq_msgsize);
561 } else {
562 StringValue(buffer);
563 rb_str_modify(buffer);
564 rb_str_resize(buffer, mq->attr.mq_msgsize);
566 OBJ_TAINT(buffer);
567 x.msg_ptr = RSTRING_PTR(buffer);
568 x.msg_len = (size_t)mq->attr.mq_msgsize;
569 x.des = mq->des;
571 if (mq->attr.mq_flags & O_NONBLOCK) {
572 r = (ssize_t)xrecv(&x);
573 } else {
574 r = (ssize_t)rb_thread_blocking_region(xrecv, &x,
575 RUBY_UBF_IO, 0);
577 if (r < 0)
578 rb_sys_fail("mq_receive");
580 rb_str_set_len(buffer, r);
582 if (wantarray)
583 return rb_ary_new3(2, buffer, UINT2NUM(x.msg_prio));
584 return buffer;
588 * call-seq:
589 * mq.attr => mq_attr
591 * Returns a POSIX_MQ::Attr struct containing the attributes
592 * of the message queue. See the mq_getattr(3) manpage for
593 * more details.
595 static VALUE getattr(VALUE self)
597 struct posix_mq *mq = get(self, 1);
598 VALUE astruct;
599 VALUE *ptr;
601 if (mq_getattr(mq->des, &mq->attr) < 0)
602 rb_sys_fail("mq_getattr");
604 astruct = rb_struct_alloc_noinit(cAttr);
605 ptr = RSTRUCT_PTR(astruct);
606 ptr[0] = LONG2NUM(mq->attr.mq_flags);
607 ptr[1] = LONG2NUM(mq->attr.mq_maxmsg);
608 ptr[2] = LONG2NUM(mq->attr.mq_msgsize);
609 ptr[3] = LONG2NUM(mq->attr.mq_curmsgs);
611 return astruct;
615 * call-seq:
616 * mq.attr = POSIX_MQ::Attr(IO::NONBLOCK) => mq_attr
618 * Only the IO::NONBLOCK flag may be set or unset (zero) in this manner.
619 * See the mq_setattr(3) manpage for more details.
621 * Consider using the POSIX_MQ#nonblock= method as it is easier and
622 * more natural to use.
624 static VALUE setattr(VALUE self, VALUE astruct)
626 struct posix_mq *mq = get(self, 1);
627 struct mq_attr newattr;
629 attr_from_struct(&newattr, astruct, 0);
631 if (mq_setattr(mq->des, &newattr, NULL) < 0)
632 rb_sys_fail("mq_setattr");
634 return astruct;
638 * call-seq:
639 * mq.close => nil
641 * Closes the underlying message queue descriptor.
642 * If this descriptor had a registered notification request, the request
643 * will be removed so another descriptor or process may register a
644 * notification request. Message queue descriptors are automatically
645 * closed by garbage collection.
647 static VALUE _close(VALUE self)
649 struct posix_mq *mq = get(self, 1);
651 if (mq_close(mq->des) < 0)
652 rb_sys_fail("mq_close");
654 mq->des = MQD_INVALID;
655 MQ_IO_SET(mq, Qnil);
657 return Qnil;
661 * call-seq:
662 * mq.closed? => true or false
664 * Returns +true+ if the message queue descriptor is closed and therefore
665 * unusable, otherwise +false+
667 static VALUE closed(VALUE self)
669 struct posix_mq *mq = get(self, 0);
671 return mq->des == MQD_INVALID ? Qtrue : Qfalse;
675 * call-seq:
676 * mq.name => string
678 * Returns the string name of message queue associated with +mq+
680 static VALUE name(VALUE self)
682 struct posix_mq *mq = get(self, 0);
684 return mq->name;
687 static int lookup_sig(VALUE sig)
689 static VALUE list;
690 const char *ptr;
691 long len;
693 sig = rb_obj_as_string(sig);
694 len = RSTRING_LEN(sig);
695 ptr = RSTRING_PTR(sig);
697 if (len > 3 && !memcmp("SIG", ptr, 3))
698 sig = rb_str_new(ptr + 3, len - 3);
700 if (!list) {
701 VALUE mSignal = rb_define_module("Signal"""); /* avoid RDoc */
703 list = rb_funcall(mSignal, rb_intern("list"), 0, 0);
704 rb_global_variable(&list);
707 sig = rb_hash_aref(list, sig);
708 if (NIL_P(sig))
709 rb_raise(rb_eArgError, "invalid signal: %s\n",
710 RSTRING_PTR(rb_inspect(sig)));
712 return NUM2INT(sig);
715 /* we spawn a thread just to write ONE byte into an fd (usually a pipe) */
716 static void thread_notify_fd(union sigval sv)
718 int fd = sv.sival_int;
720 while ((write(fd, "", 1) < 0) && (errno == EINTR || errno == EAGAIN));
723 static void setup_notify_io(struct sigevent *not, VALUE io)
725 VALUE fileno = rb_funcall(io, id_fileno, 0, 0);
726 int fd = NUM2INT(fileno);
727 pthread_attr_t attr;
728 int e;
730 if ((e = pthread_attr_init(&attr)))
731 goto err;
732 if ((e = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)))
733 goto err;
734 #ifdef PTHREAD_STACK_MIN
735 (void)pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN);
736 #else
737 # warning PTHREAD_STACK_MIN not available,
738 #endif
739 not->sigev_notify = SIGEV_THREAD;
740 not->sigev_notify_function = thread_notify_fd;
741 not->sigev_notify_attributes = &attr;
742 not->sigev_value.sival_int = fd;
743 return;
744 err:
745 rb_raise(rb_eRuntimeError, "pthread failure: %s\n", strerror(e));
749 * call-seq:
750 * mq.notify = signal => signal
752 * Registers the notification request to deliver a given +signal+
753 * to the current process when message is received.
754 * If +signal+ is +nil+, it will unregister and disable the notification
755 * request to allow other processes to register a request.
756 * If +signal+ is +false+, it will register a no-op notification request
757 * which will prevent other processes from registering a notification.
758 * If +signal+ is an +IO+ object, it will spawn a thread upon the
759 * arrival of the next message and write one "\\0" byte to the file
760 * descriptor belonging to that IO object.
761 * Only one process may have a notification request for a queue
762 * at a time, Errno::EBUSY will be raised if there is already
763 * a notification request registration for the queue.
765 * Notifications are only fired once and processes must reregister
766 * for subsequent notifications.
768 * For readers of the mq_notify(3) manpage, passing +false+
769 * is equivalent to SIGEV_NONE, and passing +nil+ is equivalent
770 * of passing a NULL notification pointer to mq_notify(3).
772 static VALUE setnotify(VALUE self, VALUE arg)
774 struct posix_mq *mq = get(self, 1);
775 struct sigevent not;
776 struct sigevent * notification = &not;
777 VALUE rv = arg;
779 if (!NIL_P(mq->thread)) {
780 rb_funcall(mq->thread, id_kill, 0, 0);
781 mq->thread = Qnil;
783 not.sigev_notify = SIGEV_SIGNAL;
785 switch (TYPE(arg)) {
786 case T_FALSE:
787 not.sigev_notify = SIGEV_NONE;
788 break;
789 case T_NIL:
790 notification = NULL;
791 break;
792 case T_FIXNUM:
793 not.sigev_signo = NUM2INT(arg);
794 break;
795 case T_SYMBOL:
796 case T_STRING:
797 not.sigev_signo = lookup_sig(arg);
798 rv = INT2NUM(not.sigev_signo);
799 break;
800 case T_FILE:
801 setup_notify_io(&not, arg);
802 break;
803 default:
804 /* maybe support Proc+thread via sigev_notify_function.. */
805 rb_raise(rb_eArgError, "must be a signal or nil");
808 if (mq_notify(mq->des, notification) < 0)
809 rb_sys_fail("mq_notify");
811 return rv;
815 * call-seq:
816 * mq.nonblock? => true or false
818 * Returns the current non-blocking state of the message queue descriptor.
820 static VALUE getnonblock(VALUE self)
822 struct posix_mq *mq = get(self, 1);
824 return mq->attr.mq_flags & O_NONBLOCK ? Qtrue : Qfalse;
828 * call-seq:
829 * mq.nonblock = boolean => boolean
831 * Enables or disables non-blocking operation for the message queue
832 * descriptor. Errno::EAGAIN will be raised in situations where
833 * the queue would block. This is not compatible with +timeout+
834 * arguments to POSIX_MQ#send and POSIX_MQ#receive.
836 static VALUE setnonblock(VALUE self, VALUE nb)
838 struct mq_attr newattr;
839 struct posix_mq *mq = get(self, 1);
841 if (nb == Qtrue)
842 newattr.mq_flags = O_NONBLOCK;
843 else if (nb == Qfalse)
844 newattr.mq_flags = 0;
845 else
846 rb_raise(rb_eArgError, "must be true or false");
848 if (mq_setattr(mq->des, &newattr, &mq->attr) < 0)
849 rb_sys_fail("mq_setattr");
851 mq->attr.mq_flags = newattr.mq_flags;
853 return nb;
856 /* :nodoc: */
857 static VALUE setnotifythread(VALUE self, VALUE thread)
859 struct posix_mq *mq = get(self, 1);
861 mq->thread = thread;
862 return thread;
865 void Init_posix_mq_ext(void)
867 cPOSIX_MQ = rb_define_class("POSIX_MQ", rb_cObject);
868 rb_define_alloc_func(cPOSIX_MQ, alloc);
869 cAttr = rb_const_get(cPOSIX_MQ, rb_intern("Attr"));
872 * The maximum number of open message descriptors supported
873 * by the system. This may be -1, in which case it is dynamically
874 * set at runtime. Consult your operating system documentation
875 * for system-specific information about this.
877 rb_define_const(cPOSIX_MQ, "OPEN_MAX",
878 LONG2NUM(sysconf(_SC_MQ_OPEN_MAX)));
881 * The maximum priority that may be specified for POSIX_MQ#send
882 * On POSIX-compliant systems, this is at least 31, but some
883 * systems allow higher limits.
884 * The minimum priority is always zero.
886 rb_define_const(cPOSIX_MQ, "PRIO_MAX",
887 LONG2NUM(sysconf(_SC_MQ_PRIO_MAX)));
889 rb_define_singleton_method(cPOSIX_MQ, "unlink", s_unlink, 1);
891 rb_define_method(cPOSIX_MQ, "initialize", init, -1);
892 rb_define_method(cPOSIX_MQ, "send", _send, -1);
893 rb_define_method(cPOSIX_MQ, "<<", send0, 1);
894 rb_define_method(cPOSIX_MQ, "receive", receive, -1);
895 rb_define_method(cPOSIX_MQ, "shift", shift, -1);
896 rb_define_method(cPOSIX_MQ, "attr", getattr, 0);
897 rb_define_method(cPOSIX_MQ, "attr=", setattr, 1);
898 rb_define_method(cPOSIX_MQ, "close", _close, 0);
899 rb_define_method(cPOSIX_MQ, "closed?", closed, 0);
900 rb_define_method(cPOSIX_MQ, "unlink", _unlink, 0);
901 rb_define_method(cPOSIX_MQ, "name", name, 0);
902 rb_define_method(cPOSIX_MQ, "notify=", setnotify, 1);
903 rb_define_method(cPOSIX_MQ, "nonblock=", setnonblock, 1);
904 rb_define_method(cPOSIX_MQ, "notify_thread=", setnotifythread, 1);
905 rb_define_method(cPOSIX_MQ, "nonblock?", getnonblock, 0);
906 #ifdef MQD_TO_FD
907 rb_define_method(cPOSIX_MQ, "to_io", to_io, 0);
908 #endif
910 id_new = rb_intern("new");
911 id_kill = rb_intern("kill");
912 id_fileno = rb_intern("fileno");
913 sym_r = ID2SYM(rb_intern("r"));
914 sym_w = ID2SYM(rb_intern("w"));
915 sym_rw = ID2SYM(rb_intern("rw"));