How to access Parallel port in Linux

Xiaobo Zhang picture Xiaobo Zhang · Jul 25, 2013 · Viewed 13.2k times · Source

On my Linux machine (Debian Wheezy), I tried to access the parallel port by request_region() but it failed because the system had already loaded the kernel module parport...

So, I rmmod the modules lp, ppdev, parport_pc and parport. Then, I could successfully insert my module.

However, from the base address inb() returned 0xff, no matter what value was written.

Before rmmod those module from kernel, I could wrote and read this register. Then I blacklisted those module from being loaded at system start up, and I could read and write these registers and my module also worked. It seems that the clearup function of parport_pc did something that made the hardware unusable. (At least the status of the port is not the same as it was before the module loaded).

My question is why, and what should I do to recover the port instead of reload parport_pc ?

Answer

mti2935 picture mti2935 · Jul 25, 2013

You can use C to write a small program that will read and write directly from/to the pins on the parallel port by way of the outb and inb functions. Then, you can simply call the C program from the command line of shelling from some other script. Usually, (by default) address 0x378 is the address of the parallel port LPT0 in memory, so you it's just a matter of using inb and outp to read/write to this address. For example:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <asm/io.h>

#define base 0x378   //LPT0

//to compile:  gcc -O parport.c -o parport
//after compiling, set suid:  chmod +s parport   then, copy to /usr/sbin/


int main(void) {
  if(ioperm(base,1,1)) 
    fprintf(stderr, "Couldn't open parallel port"), exit(1);

  outb(255,base);  //set all pins hi
  sleep(5); 
  outb(0,base);    //set all pins lo

  return 0;
}