0

我想使用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”均为空且未初始化。

4

1 回答 1

0

它是通过使用中间无符号字符缓冲区来初始化第二个应用程序中的 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;

}
# ...
于 2019-03-07T06:52:21.280 回答