当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - 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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: