1

I wrote the following code to understand how nonblocking write is operated:

import os, time

def takeAnap():
    print('I am sleeping a bit while it is writing!')
    time.sleep(50)

fd = os.open('t.txt', os.O_CREAT | os.O_NONBLOCK)
for i in range(100):
    # Non-blocking write
    fd = os.open('t.txt', os.O_APPEND | os.O_WRONLY | os.O_NONBLOCK)
    os.write(fd, str(i))
    os.close(fd)
    time.sleep(2)
takeAnap()

As you can see, I am creating takeAnap() to be activated while the loop is being processed so that I can convince my self that the writing is performed without blocking! However, the loop still blocks and the method is not performed until finishing. I am not sure if my understanding is wrong but as far as I know, non-blocking operation allows you to do other tasks while the writing is being processed. Is that correct? If so, kindly where is the problem in my code!

Thank you.

cs95
  • 379,657
  • 97
  • 704
  • 746
Ahmad
  • 85
  • 6

1 Answers1

1

I think you misunderstand what the O_NONBLOCK flag is used for. Here's what the flag actually does:

This prevents open from blocking for a “long time” to open the file. This is only meaningful for some kinds of files, usually devices such as serial ports; when it is not meaningful, it is harmless and ignored.

Excerpt from https://www.gnu.org/software/libc/manual/html_node/Open_002dtime-Flags.html.

So, the flag does not specify non-blocking write, but non-blocking open. The writing is still serial, and blocking, and slow.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • Thank you very much. The notion of non-blocking is then related to reading from disk. Is that correct? – Ahmad Mar 16 '18 at 21:33
  • @SteveMcarthy It depends on the context being used. In this case, the flag is only in the context of opening files (and is considered only in a select few cases). – cs95 Mar 16 '18 at 21:34
  • @SteveMcarthy Furthermore, you may want to consider that "asynchronous IO" and "non-blocking IO" don't mean the same thing. See https://stackoverflow.com/a/983764/4909087 for more. – cs95 Mar 16 '18 at 21:35
  • I was told that write can be non-blocking as well so that is why I am trying this example! Thank you for clarifying – Ahmad Mar 16 '18 at 21:36
  • @SteveMcarthy I think it can (not sure), but certainly this flag is ignored for regular files, that I can guarantee. – cs95 Mar 16 '18 at 21:43