linux c检测网口断开,在Linux中使用termios API(C ++)检测字符设备是否已断开连接...

小编典典

首先值得一提的是,serial-usb的行为如下:

在USB设备上,拔出的断开连接称为

@disconnect:当不再可访问该接口时调用,通常是因为其设备已(或正在)断开连接或正在卸载驱动程序模块。

在我们的例子中是usb_serial_disconnect(struct usb_interface * interface)

调用usb_serial_console_disconnect(serial),调用tty_hangup …,依此类推。

您可以遵循从这里开始的链条:http : //lxr.free-electrons.com/source/drivers/usb/serial/usb-serial.c#L1091

简而言之,这导致以下经典方式:

pselect表示文件描述符已准备就绪,并且ioctl(fd,FIONREAD和&len)返回零len。

就是这样,您拔出了设备。

求和(来自您的代码):

while(1)

{

FD_ZERO(&rfds);

FD_SET(tty_fd, &rfds);

// have tried checking fcntl(tty_fd, F_GETFL); too

// Blocking call to wait until we have data

int ready = select(tty_fd + 1, &rfds, NULL, NULL, NULL);

if(ready && FD_ISSET(tty_fd, &rfds)) {

size_t len = 0;

ioctl(tty_fd, FIONREAD, &len);

errsv = errno;

if(len == 0)

{

printf("prog_name: zero read from the device: %s.", strerror(errsv));

/* close fd and cleanup or reconnect etc...*/

exit(EXIT_FAILURE);

}

// While we have data, collect it

while (read(tty_fd, &c, 1)>0 && bytesRead++<200)

{

serialBuffer.push_back(c);

}

bytesRead = 0;

// Try to parse it

BufferParse();

}

}

很遗憾您没有说明您使用的是哪种设备。

如果您的设备能够进行RTS / CTS流量控制,则还可以检测到线路中断。

2020-06-07

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值