module ExtremeTimeout

Public Class Methods

timeout(p1, p2 = v2, &block) click to toggle source

NOTE: Exposing this function name “timeout” caused segmentation fault in some environment (See PR #6).

static VALUE
timeout(int argc, VALUE *argv, VALUE self)
{
    int exitcode = 1, state;
    unsigned int timeout_sec = 0;
    VALUE timeout_sec_value, exitcode_value, block;
    pthread_t thread;
    struct wait_args arg;
    VALUE retval;

    rb_scan_args(argc, argv, "11&", &timeout_sec_value, &exitcode_value, &block);

    if (!FIXNUM_P(timeout_sec_value)) {
        rb_raise(rb_eArgError, "the timeout argument should be Fixnum");
    }
    timeout_sec = FIX2UINT(timeout_sec_value);

    exitcode = 1;
    if (exitcode_value != Qnil) {
        if (!FIXNUM_P(exitcode_value)) {
            rb_raise(rb_eArgError, "the exitcode argument should be Fixnum");
        }
        exitcode = FIX2INT(exitcode_value);
    }

    if (block == Qnil) {
        rb_raise(rb_eArgError, "expects block");
    }

    arg.timeout_sec = timeout_sec;
    arg.exitcode = exitcode;
    arg.running_thread = pthread_self();
    if (pthread_create(&thread, NULL, sleep_thread_main, &arg) != 0) {
        rb_raise(rb_eRuntimeError, "pthread_create was failed");
    }

    retval = rb_protect(timeout_cb, block, &state);

    pthread_cancel(thread);
    pthread_join(thread, NULL);
    return retval;
}