Re: Using fcntl ( ioctl, actually )

Steven D. Majewski (sdm7g@elvis.med.virginia.edu)
Tue, 15 Mar 1994 17:57:37 -0500

Here's a sample function using ioctl to get the terminal
screen size. The [T]IOC* defs are from my <sys/ioctl.h>.
There is no reason that I know of to expect them to be portable.
Note that the setwinsize() doesn't do anything PHYSICAL -
it's basically the same as if you had done a 'stty rows $N cols $M' .

[ Does anyone know if there is a non-X way to Physically change
the size of an xterm window? i.e. is there an ascii sequence
as in setting the title. ]

I did this to try to figure out how to use it myself, - it's
not explained or documented because I haven't figured it all
out myself. ( And that's also why there is an extra function to
return the raw return string. )

Good Luck.

- Steve Majewski (804-982-0831) <sdm7g@Virginia.EDU>
- UVA Department of Molecular Physiology and Biological Physics

#----------------------------------------------------------------
from fcntl import *
import struct

IOC_OUT = 0x40000000
IOC_IN = 0x80000000
TIOCSWINSZ = 103
TIOCGWINSZ = 104

H4 = 'hhhh'
Hsize = struct.calcsize( H4 )
GETWS = IOC_OUT | ( ord('t') << 8 ) | TIOCGWINSZ
SETWS = IOC_IN | ( ord('t') << 8 ) | TIOCSWINSZ

def _getwinsize( fd ):
return ioctl( fd, GETWS | ( Hsize << 16 ), Hsize*'\000' )

def getwinsize( fd ):
if type(fd) <> type(0): fd = fd.fileno()
size = struct.unpack( H4, _getwinsize(fd) )[:2]
return ( size[0], size[1] )

def setwinsize( fd, rows, cols ):
if type(fd) <> type(0): fd = fd.fileno()
ws = struct.pack( H4, rows, cols,0,0 )
ioctl( fd, SETWS | (len(ws) << 16), ws )

import posix
t = posix.open( '/dev/tty', 2, 0 )

rows,cols = getwinsize(t)
print '/dev/tty Window size = ', ( rows,cols )
print 'Changing size to ', ( rows+5, cols-10 )
setwinsize( t, rows+5, cols-10 )