Method: IO#write_nonblock

Defined in:
io.c

#write_nonblock(string) ⇒ Integer #write_nonblock(string[, options]) ⇒ Integer

Writes the given string to ios using the write(2) system call after O_NONBLOCK is set for the underlying file descriptor.

It returns the number of bytes written.

write_nonblock just calls the write(2) system call. It causes all errors the write(2) system call causes: Errno::EWOULDBLOCK, Errno::EINTR, etc. The result may also be smaller than string.length (partial write). The caller should care such errors and partial write.

If the exception is Errno::EWOULDBLOCK or Errno::AGAIN, it is extended by IO::WaitWritable. So IO::WaitWritable can be used to rescue the exceptions for retrying write_nonblock.

# Creates a pipe.
r, w = IO.pipe

# write_nonblock writes only 65536 bytes and return 65536.
# (The pipe size is 65536 bytes on this environment.)
s = "a" * 100000
p w.write_nonblock(s)     #=> 65536

# write_nonblock cannot write a byte and raise EWOULDBLOCK (EAGAIN).
p w.write_nonblock("b")   # Resource temporarily unavailable (Errno::EAGAIN)

If the write buffer is not empty, it is flushed at first.

When write_nonblock raises an exception kind of IO::WaitWritable, write_nonblock should not be called until io is writable for avoiding busy loop. This can be done as follows.

begin
  result = io.write_nonblock(string)
rescue IO::WaitWritable, Errno::EINTR
  IO.select(nil, [io])
  retry
end

Note that this doesn’t guarantee to write all data in string. The length written is reported as result and it should be checked later.

On some platforms such as Windows, write_nonblock is not supported according to the kind of the IO object. In such cases, write_nonblock raises Errno::EBADF.

By specifying ‘exception: false`, the options hash allows you to indicate that write_nonblock should not raise an IO::WaitWritable exception, but return the symbol :wait_writable instead.

Overloads:



2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
# File 'io.c', line 2784

static VALUE
rb_io_write_nonblock(int argc, VALUE *argv, VALUE io)
{
    VALUE str;
    VALUE opts = Qnil;
    int no_exceptions = 0;

    rb_scan_args(argc, argv, "10:", &str, &opts);

    if (!NIL_P(opts) && Qfalse == get_kwargs_exception(opts))
	no_exceptions = 1;

    return io_write_nonblock(io, str, no_exceptions);
}