简体   繁体   中英

Serial port is stuck at wait(4,

I have this implementation in C++ for linux for initializing a serial port:

void setupSerialPort()
{
    fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);       

    memset(&tio, 0, sizeof(tio));
    tio.c_iflag = 0;
    tio.c_oflag = 0;
    tio.c_cflag = CS8|CREAD|CLOCAL;                 
    tio.c_lflag = 0;
    tio.c_cc[VMIN] = 0;                             
    tio.c_cc[VTIME] = 0;                                

    fd = open(SERIALPORT, O_RDWR | O_NONBLOCK) ;                

    fcntl(fd , F_SETFL, 0);     // read data in the buffer per chunk

    cfsetospeed(&tio, B4800);             // 4800 baud
    cfsetispeed(&tio, B4800);             // 4800 baud

    tcsetattr(fd , TCSANOW, &tio);
}

Sometimes, the serial port reading is stuck and I use 'strace' to see what is going on. the problem is:

strace -p 9454
Process 9454 attached - interrupt to quit
wait4(-1, ^C <unfinished ...>
Process 9454 detached

How can I avoid the problem (it does not happen all the time)?

The problem occurring randomly indicates that the call to open is failing. So check the return values from open call and other remaining calls.

if (fd < 0) return;

Also ensure clean close of the serial port.

Syscalls involving IO could get stuck specially with network IO. Since you are using NON_BLOCKING mode that shouldnt be the case , The complete code would have been helpful here. Personally i had this situation before and I used timer to generate SIG_USR which used to end the blocking call with an error. Pseudo code for that algo is as follows:

 initiateTimer ( timeout)
     myfunctionCall(){
        someSysCall();
     }
  if(!signalled){
    disableTimer();
  }else{
     checkState();
     if(fatal)
       die;
   }

My suggestions... Open the device with:

int fd = TEMP_FAILURE_RETRY(open(ttyName, O_RDWR | O_NOCTTY | O_NONBLOCK));

The macro TEMP_FAILURE_RETRY is needed to protect open, close, read and select from signal interruptions. Read about the macro if you use libc. Include O_NOCTTY flag to avoid the device becoming the controlling port of the process. Check return value for valid fd.


C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM