You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ORSSerialPort接收数据完成后如何立即终止程序?

ORSSerialPort 接收数据后自动终止程序的实现方案

问题原因

RunLoop.main.run()会让主RunLoop进入无终止条件的无限循环,没有外部触发的情况下会一直运行,导致程序无法退出。

具体实现方案

你只需要在串口的接收回调中主动终止主RunLoop即可,还可以增加超时机制兜底避免程序永久卡住:

  • 配置ORSSerialPort的接收回调,当收到预期数据后调用CFRunLoopStop(CFRunLoopGetMain())停止主RunLoop
  • 将无参数的RunLoop.main.run()替换为带超时时间的版本,超时后自动结束RunLoop

代码示例

import ORSSerial

// 替换为你的串口设备路径
guard let serialPort = ORSSerialPort(path: "/dev/tty.usbserial-XXXX") else {
    exit(1)
}
// 配置串口参数
serialPort.baudRate = 9600
serialPort.parity = .none
serialPort.stopBits = 1
serialPort.open()

// 设置数据接收回调
serialPort.didReceiveData = { _, receivedData in
    // 可根据业务需求增加数据校验逻辑,校验通过再终止RunLoop
    print("接收到数据:\(receivedData)")
    // 主动终止主RunLoop
    CFRunLoopStop(CFRunLoopGetMain())
}

// 发送测试数据
serialPort.send("test".data(using: .utf8)!)

// RunLoop最多运行10秒,超时后即使未收到数据也会退出,可根据需求调整超时时间
RunLoop.main.run(until: Date().addingTimeInterval(10))

// RunLoop停止后执行退出逻辑
serialPort.close()
exit(0)

提示:如果需要确保收到完整应答再退出,可以在didReceiveData回调中先判断数据长度、匹配应答关键字,满足条件再调用终止方法,避免提前退出丢失数据。

内容的提问来源于stack exchange,提问作者klg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 14:36:02