1

I am writing C++ class (SerialPort) in order to use it in 2 threads (one object for each with shared descriptor). I want to send data in first thread and receive data in second. It works as expected. But I want to do it right. And I want my app resist heavy trafic (in the cases Linux output buffer is full very often). So I use pselect in SerialPort::receive() and it works as expected. But when I use it in SerialPort::send() it does not block when output buffer is full!!! I am able to detect this situation with ioctl, but I am unable to wait for some free space in this buffer. So active waiting loop is happen witch simply hangs the app!!! Note: I wrote about Linux serial port output buffer, not my app serial output buffer (I alocate 1MB for it, and it works as expected). Bellow I paste functions SerialPort::receive() and SerialPort::send() and pease give me some hints how to avoid active waiting loop in cases serial port otuput buffer is full...

thanks in advance and best regards Jacek

ps1: Here is my code (error messages are in polish due to previous developers customs - it is not mine decision, it is just required by translation tools in order to keep translation process consistent):

void SerialPort::receive()
{
// http://www.linuxprogrammingblog.com/code-examples/using-pselect-to-avoid-a-signal-race
// https://www.cmrr.umn.edu/~strupp/serial.html
    if(mPortDescriptor < 0)
        throw Exception(tr("Zły deskryptor pliku: %1").arg(mPortDescriptor).toUtf8().data());

    struct sigaction lSigAction;
    memset (&lSigAction, 0, sizeof(lSigAction));
    lSigAction.sa_handler = gSignTermHandler;

    // This server should shut down on SIGTERM.
    if(sigaction(SIGTERM, &lSigAction, 0))
        throw Exception(tr("Błąd sigaction! %1, %2").arg(errno).arg(strerror(errno)));

    sigset_t lMask;
    sigemptyset (&lMask);
    sigaddset (&lMask, SIGTERM);

    sigset_t orig_mask;
    if(sigprocmask(SIG_BLOCK, &lMask, &orig_mask) < 0)
        throw Exception(tr("Błąd sigprocmask! %1, %2").arg(errno).arg(strerror(errno)));

    struct timespec timeout;
    timeout.tv_sec  = 1;
    timeout.tv_nsec = 0;

    fd_set lFileDescriptorSet;
    /* BANG! we can get SIGTERM at this point, but it will be
     * delivered while we are in pselect(), because now
     * we block SIGTERM.
     */
    FD_ZERO(&lFileDescriptorSet);
    FD_SET(mPortDescriptor, &lFileDescriptorSet);

    while(true)
    {
        int lRes = pselect(mPortDescriptor + 1, &lFileDescriptorSet, NULL, NULL, &timeout, &orig_mask);
        if(mEnd)
            return;
        if((lRes < 0) && (errno != EINTR))
            throw Exception(tr("Bład pselect! %1, %2").arg(errno).arg(strerror(errno)));
        if(lRes == 0)  // timeout
            continue;
        if(gExitRequest)
            throw Exception(tr("Przechwycono sygnał SIGTERM! Koniec odbierania danych."));
        if(!FD_ISSET(mPortDescriptor, &lFileDescriptorSet))
            continue;

        int lSize = 0;
        ioctl(mPortDescriptor, FIONREAD, &lSize);

        if(lSize <= 0)
            continue;

        QByteArray lResult;
        lResult.resize(lSize);
        int lReaded(0), lPartial(0);
        while(lReaded < lSize)
        {
            if(mEnd)
                return;
            lPartial = ::read(mPortDescriptor, lResult.data(), lSize);
            if(lPartial > 0)
                lReaded += lPartial;
            else if(lPartial < 0)
            {
                qCritical() << tr("Uwaga! Błąd czytania portu szeregowego! Kod błędu: %1, wiadomość: %2").arg(errno).arg(strerror(errno));
                break;
            }
        }                    
        emit read(lResult);
    }
}

void SerialPort::send()
{
    // http://www.linuxprogrammingblog.com/code-examples/using-pselect-to-avoid-a-signal-race
    // https://www.cmrr.umn.edu/~strupp/serial.html
    if(mPortDescriptor < 0)
        throw Exception(tr("Zły deskryptor pliku: %1").arg(mPortDescriptor).toUtf8().data());

    struct sigaction lSigAction;
    memset (&lSigAction, 0, sizeof(lSigAction));
    lSigAction.sa_handler = gSignTermHandler;

    // This server should shut down on SIGTERM.
    if(sigaction(SIGTERM, &lSigAction, 0))
        throw Exception(tr("Błąd sigaction! %1, %2").arg(errno).arg(strerror(errno)));

    sigset_t lMask;
    sigemptyset(&lMask);
    sigaddset(&lMask, SIGTERM);

    sigset_t orig_mask;
    if(sigprocmask(SIG_BLOCK, &lMask, &orig_mask) < 0)
        throw Exception(tr("Błąd sigprocmask! %1, %2").arg(errno).arg(strerror(errno)));

    struct timespec timeout;
    timeout.tv_sec  = 1;
    timeout.tv_nsec = 0;

    fd_set lFileDescriptorSet;
    /* BANG! we can get SIGTERM at this point, but it will be
     * delivered while we are in pselect(), because now
     * we block SIGTERM.
     */
    FD_ZERO(&lFileDescriptorSet);
    FD_SET(mPortDescriptor, &lFileDescriptorSet);

    int lNumberToAquire(0);
    while(true)
    {
        lNumberToAquire = 0;
        if(mBufferEnd > mBufferStart)
            lNumberToAquire = mBufferEnd - mBufferStart;
        else if(mBufferEnd < mBufferStart)
            lNumberToAquire = mSendBuffer.size() - mBufferStart;
        if(lNumberToAquire <= 0)
            lNumberToAquire = 1;

        int lFreeSpaceSize = 0;
        ioctl(mPortDescriptor, TIOCOUTQ, &lFreeSpaceSize);
        if(lFreeSpaceSize <= 0) // we must wait for serial port
        {
            int lRes = pselect(mPortDescriptor + 1, NULL, &lFileDescriptorSet, NULL, &timeout, &orig_mask);
            if(mEnd)
                return;
            if((lRes < 0) && (errno != EINTR))
                throw Exception(tr("Bład pselect! Kod błedu: %1, komunikat: %2").arg(errno).arg(strerror(errno)));
            if(lRes == 0)  // timeout
                continue;
            if(gExitRequest)
                throw Exception(tr("Przechwycono sygnał SIGTERM! Koniec wysyłania danych."));
            if(!FD_ISSET(mPortDescriptor, &lFileDescriptorSet))
                continue;
        }

        ioctl(mPortDescriptor, TIOCOUTQ, &lFreeSpaceSize);

        if(lFreeSpaceSize <= 0)
        {
            qWarning() << tr("%1 Uwaga: Brak miejsca w bufoerze wyjściowym portu szeregowego!").arg(QTime::currentTime().toString("hh:mm:ss.z"));
            continue;
        }

        lNumberToAquire = qMin(lNumberToAquire, lFreeSpaceSize);

//#ifdef DEBUG
//        int lSemaphore(mAvailableData.available());
//#endif
        if((lNumberToAquire > 0) && mAvailableData.tryAcquire(lNumberToAquire, 1000))
        {
//#ifdef DEBUG
//        int lSemaphore2(mAvailableData.available());
//#endif                
            int lWriten(0), lPartial(0);
            while(lWriten < lNumberToAquire)
            {
                lPartial = ::write(mPortDescriptor, mSendBuffer.data() + mBufferStart, lNumberToAquire);
                if(lPartial > 0)
                    lWriten += lPartial;
                else if(lPartial < 0)
                {
                    qCritical() << tr("Błąd zapisu do portu szeregowego!!! Kod błędu: %1, Wiadomość błędu: %2").arg(errno).arg(strerror(errno));
                    break;
                }
            }

//            qDebug() << QTime::currentTime().toString("hh:mm:ss.z") << "Write to the serial port.";
            mBufferStart = (mBufferStart + lNumberToAquire) % mSendBufferSize;
            mFreeSpace.release(lNumberToAquire);
        }
        if(mEnd)
            return;
    }
} 

EDIT: I found solution! I have bug with pselect usage: I do not reinitialize fd_set lFileDescriptorSet; after first usage. It need to be reinitialized before each call:

FD_ZERO(&lFileDescriptorSet);
FD_SET(mPortDescriptor, &lFileDescriptorSet);

According to this site: [How can I determine the amount of write/output buffer space left on a linux serial port? Bogdan-Stefan Mirea wrote:

The serial port is a character device not a block device. It has no buffer

But some other sources claims Linux has 4KB serial port buffer though. Follow his advice I worte function with loop with pselect call (waiting for serial port write readines), and write only 1 byte per iteration. And it works!!!

0 Answers0