我想编写一个在串口上模拟设备的程序.我正在尝试使用伪终端来实现这一目标.我想要一个独特的过程来控制主人.此过程充当串行设备模拟器.我希望另一个进程(例如kermit)能够使用从终端与主站通信.由于不同的工艺要求,我没有使用任何叉子.几乎互联网上的每个伪终端示例都显示了fork()用于主/从.
我让它在一个方向上工作.也就是说,我可以让从属进程将数据写入从属伪终端,并且主机将从主假终端读取它就好了.
问题出在另一个方向.我无法让master写入数据和slave来读取数据.
我将展示非工作双向代码和工作单向代码.
非工作双向主控:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char* argv[])
{
// get the master fd
int masterfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
if(masterfd < 0)
{
perror("getpt");
exit(1);
}
// grant access to the slave
if(grantpt(masterfd) < 0)
{
perror("grantpt");
exit(1);
}
// unlock the slave
if(unlockpt(masterfd) < 0)
{
perror("unlockpt");
exit(1);
}
// get the path to the slave
char slavepath[64];
if(ptsname_r(masterfd, slavepath, sizeof(slavepath)) < 0)
{
perror("ptsname_r");
exit(1);
} …Run Code Online (Sandbox Code Playgroud)