distinct fcntl flags for stdin and stdout

Nick Craig-Wood nick at craig-wood.com
Mon Dec 1 06:30:44 EST 2008


mbuna <sthiell at gmail.com> wrote:
>  Hello,
>  when I set non blocking flag with fcntl on sys.stdin, then sys.stdout
>  turns into non blocking mode too. Is it normal behaviour? How can I
>  turn stdin into non blocking mode but not stdout? Thanks.
> 
>  This is a quick program that shows the (my?) problem:
> 
>  import fcntl
>  import os
>  import sys
> 
>  print "STDIN", sys.stdin, "fd=%d" % sys.stdin.fileno()
>  print "STDOUT", sys.stdout, "fd=%d" % sys.stdout.fileno()
>  print "os.O_NDELAY=%04x" % os.O_NDELAY
>  def state():
>      flag = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL)
>      print "stdin: flag=%04x" % flag
>      flag = fcntl.fcntl(sys.stdout.fileno(), fcntl.F_GETFL)
>      print "stdout: flag=%04x" % flag
>  state()
>  print "setting non blocking on stdin..."
>  flag = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL)
>  fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, flag | os.O_NDELAY)
>  state()
>  print "removing non blocking on stdin..."
>  flag = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL)
>  fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, flag & ~os.O_NDELAY)
>  state()
> 
> 
>  RESULT
>  STDIN <open file '<stdin>', mode 'r' at 0x2aaaaaacd120> fd=0
>  STDOUT <open file '<stdout>', mode 'w' at 0x2aaaaaacd198> fd=1
>  os.O_NDELAY=0800
>  stdin: flag=8002
>  stdout: flag=8002
>  setting non blocking on stdin...
>  stdin: flag=8802
>  stdout: flag=8802
>  removing non blocking on stdin...
>  stdin: flag=8002
>  stdout: flag=8002

If you try this with output redirected to a file, you get this (under
linux)

STDIN <open file '<stdin>', mode 'r' at 0xb7d03020> fd=0
STDOUT <open file '<stdout>', mode 'w' at 0xb7d03068> fd=1
os.O_NDELAY=0800
stdin: flag=0002
stdout: flag=8001
setting non blocking on stdin...
stdin: flag=0802
stdout: flag=8001
removing non blocking on stdin...
stdin: flag=0002
stdout: flag=8001

So I suspect your result is because stdin and stdout refer to the same
file (eg /dev/tty0 or /dev/pts/25).

No idea whether this is correct behaviour or not though!

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list