gpt4 book ai didi

nim-lang - 如何忽略 nim 中的 "broken pipe"异常

转载 作者:行者123 更新时间:2023-12-02 16:28:51 25 4
gpt4 key购买 nike

我正在编写一个 CLI 程序,当我执行像 program | 这样的二进制文件时头 我得到:

Error: unhandled exception: errno: 32 `Broken pipe` [IOError]

我想消除这个异常并尝试添加:

import posix
signal(SIG_PIPE, SIG_IGN)

在我的主要程序中,但这并没有消除错误。该程序使用 threadspool,调用另一个过程来分析输入行池。 (我不知道这是否与问题有关)

更新:

  • 这是我的非工作程序:https://pastebin.com/aQaRgfXR (使用 responses.add(spawn parseArray(readspool, mergeOptions)) 产生的线程)
  • 这是完整的错误:
/Users/telatina/miniconda3/nim/lib/pure/concurrency/threadpool.nim(377) slave
/Users/telatina/git/nim-stuff/orf/src/porfidus.nim(307) parseArrayWrapper
/Users/telatina/git/nim-stuff/orf/src/porfidus.nim(247) parseArray
/Users/telatina/miniconda3/nim/lib/system/io.nim(155) checkErr
/Users/telatina/miniconda3/nim/lib/system/io.nim(138) raiseEIO
Error: unhandled exception: errno: 0 `Undefined error: 0` [IOError]

最佳答案

基于@julian-fondren 的回答和您的代码,我能够重现您的错误。

import os, posix, threadpool
signal(SIG_PIPE, SIG_IGN)

proc noise =
for i in 0 ..< int(1e6):
stdout.write($i & '\n')

threadpool.spawn noise()
threadpool.spawn noise()
threadpool.sync()

对于跟随者。

您也在代码中使用了 stdout.writemay throw an IO Exception
由于您使用 SIG_IGN 线程在收到 SIG_PIPE 时不会停止运行,而是继续在损坏的管道上调用 stdout.write,这会抛出异常。

为了解决这个问题,我找到了三个选项

  1. 处理异常

    这是最通用的解决方案,适用于您的代码因“错误:未处理的异常”而崩溃的任何情况

    to handle an exception in Nim使用 tryexcept

stdout.write($i & '\n') 变成

try:
stdout.write($i & '\n')
except IOError:
#handle it by ending the program
quit()
#or ignore it with
#discard
  1. 处理信号在我的机器上使用 SIG_DFL 会导致线程静默终止,从而按照您的意愿运行,但这取决于平台。所以你也可以注册你自己的信号处理程序(对不起,丑陋的造型)
#signal(SIG_PIPE,SIG_DFL)
signal(SIG_PIPE,cast[typeof(SIG_IGN)](proc(signal:cint) =
stderr.write("handled sigpipe\n")
quit()
))
  1. 只需使用回显echo,与 stdout.write 不同,它不会抛出异常,因此对于这种情况,这可能是最简单的解决方法

关于nim-lang - 如何忽略 nim 中的 "broken pipe"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63886311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com