python ioctl

Neal Becker ndbecker2 at
Thu Apr 14 15:25:02 CEST 2011

Nitish Sharma wrote:

> Hi PyPpl,
> For my current project I have a kernel device driver and a user-space
> application. This user-space application is already provided to me, and
> written in python. I have to extend this application with some addition
> features, which involves communicating with kernel device driver through
> ioctl() interface.
> I am fairly new with Python and not able to grok how to provide "op" in
> ioctl syntax - fcntl.ioctl (fd, op[, arg[, mutate_flag]]). Operations
> supported by device driver, through ioctl, are of the form: IOCTL_SET_MSG
>  _IOR(MAGIC_NUMBER, 0, char*).
> It'd be great if some help can be provided about how to "encode" these
> operations in python to implement the desired functionality.
> Regards
> Nitish
Here's some of my stuff.  Specific to my device, but maybe you get some ideas

-------- ----
from ctypes import *

libc = CDLL ('/lib/')
#print libc.ioctl

def set_ioctl_argtype (arg_type):
    libc.ioctl.argtypes = (c_int, c_int, arg_type)




def IOC (dir, type, nr, size):
    return (((dir)  << _IOC_DIRSHIFT) | \
	 ((type) << _IOC_TYPESHIFT) | \
	 ((nr)   << _IOC_NRSHIFT) | \
	 ((size) << _IOC_SIZESHIFT))

def ioctl (fd, request, args):
    return libc.ioctl (fd, request, args)

example of usage:

    # Enable byte swap in driver
    from eioctl import IOC, IOC_WRITE

    EOS_IOC_MAGIC = 0xF4

    request = IOC(IOC_WRITE, EOS_IOC_MAGIC, 1, struct.calcsize ('i'))
    err = fcntl.ioctl(eos_fd, request, 1)

More information about the Python-list mailing list