从ipc fifo文件描述符读取缓冲区时未初始化QDataStream

时间:2019-03-02 16:28:51

标签: qt ipc fifo mkfifo qdatastream

我想使用fifo(ipc)在两个应用程序之间进行通信,我已经通过“ mkfifo MyPipe”命令创建了一个fifo。

第一个应用程序:

....
....
fd = open("MyPipe", O_NONBLOCK | O_WRONLY);

QByteArray buf;
QDataStream bdwr(&buf,QIODevice::WriteOnly);
bdwr.setVersion(kDSVersion);

myclassObjWr.lname = "AAAAA";
myclassObjWr.fname = "BBBBB";

bdwr << myclassObjWr.lname << myclassObjWr.fname ;

ssize_t written = write(fd,buf.data() , buf.length());

.....
.....

第二个应用程序:

....
....
fd = open("MyPipe", O_NONBLOCK | O_RDONLY);
ssize_t nread;
QByteArray rxbuf;
static const QDataStream::Version kDSVersion = QDataStream::Qt_5_12;
QDataStream bdrd(&rxbuf, QIODevice::ReadWrite);
bdrd.setVersion(kDSVersion);

nread = read(fd, rxbuf.data(),200);

if ( nread > 0)
{
    bdrd.writeRawData(rxbuf.data(),nread);
    bdrd >> myclassObjrd.lname >> myclassObjrd.fname;  
    qDebug() << "lname: " << myclassObjrd.lname;
}
....

....

在读取ipc fifo之后,“ rxbuf”已完全初始化,但是“ myclassObjrd.lname”和“ myclassObjrd.fname”都为空且未初始化。

1 个答案:

答案 0 :(得分:0)

通过在第二个应用程序中使用中间无符号char缓冲区初始化QByteArray来解决此问题,

# ...
ssize_t nread;

QByteArray buf;

unsigned char* rxbuf;

static const QDataStream::Version kDSVersion = QDataStream::Qt_5_12;

QDataStream bdrd(&buf, QIODevice::ReadOnly);

bdrd.setVersion(kDSVersion);

rxbuf = (unsigned char*)malloc(200);

nread = read(fd, rxbuf,200);

if ( nread > 0)
{

   for (int i = 0 ; i < nread; i++) {

   buf[i] = rxbuf[i] ;   //init QByteArray

   }

bdrd >> myclassObjrd.lname >> myclassObjrd.fname;  

qDebug() << "lname: " << myclassObjrd.lname;

}
# ...