1

I want to set a serial port in Linux to "raw" mode at 115200 baud. If I run the following program

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

int main(int argc, char **argv)
{
  int fd= open( "/dev/ttyS0", O_RDWR );


  if ( fd < 0 )
    {
      perror(0);
      int err = errno;
      fprintf( stderr, "can't open /dev/ttyS0 got err %d\n",err );
      return err;
    }
  printf("got fd %d\n", fd );


  struct termios old;

  tcgetattr(fd,&old);

  struct termios news;
  // enable raw comms
  cfmakeraw( &news);

  // set port to 115200 baud
  cfsetispeed(&news, B115200);
  tcsetattr( fd, TCSANOW,&news);

  printf("set raw 115200\n");

  usleep(5000000);

  printf( "slept\n");

  tcsetattr( fd, TCSANOW,&old);

  printf( "restored\n");

  close(fd);

  printf("closed\n");
}

and interrupt it during the sleep with Ctrl-C, then run it again, there is no output the second time - the program hangs during the open() call. Even running as root doesn't help.

There is no indication the first process is still using the port or that the port is locked, nothing is apparent in /var/lock/ or ps aux | grep tty

My best option right now is to ensure that whenever a process using a tty is terminated it correctly closes the port. But why should this problem arise at all? Shouldn't the aborted process release the port?

4

1 回答 1

1

On my system, I found out that it was caused by a module called 'option'. After doing 'modprobe -r option', I could open the serial port without any problem.

于 2011-07-30T12:27:09.517 回答