6

I have this function _write_port() being called from a thread, whenever I need to send a message. To ensure the whole message is written, tcdrain() is used.

void Serial_Port::_write_port(char *buf, unsigned &len)
{

    // Lock
    pthread_mutex_lock(&lock);

    // Write packet via serial link
    write(fd, buf, len);

    // Wait until all data has been written
    tcdrain(fd);

    // Unlock
    pthread_mutex_unlock(&lock);

    return;
}

My problem is that tcdrain() blocks forever after a random number of executions of this function _write_port(). This will block the lock, resulting in blocking my other read thread, resulting in blocking everything.

What is a good approach to avoid tcdrain from blocking forever?


Note: I strangely noticed that if I use several printf() throughout the function, tcdrain never blocks. It does not make any sense to me to exist a relationship between printf() and write() because they write to different output files. Since I cannot explain this behaviour I assume it may be a coincidence that it worked like this on my experiments. If someone can explain this behaviour, please let me know.

jose
  • 220
  • 1
  • 12
  • I'm having the same problems with a home brewed solution. I'm using 3DR v2 915 MHz radios. What hardware are you using? – Constantin Jul 23 '15 at 02:46
  • I'm also having the same issue. Did you find a solution? In my case I'm writing on a USB link from a Linux machine to an STM32-based autopilot. – clem Dec 16 '21 at 13:18

0 Answers0