可移植地在一个会话中多次打开标准输入的句柄 [英] Portably opening a handle to stdin many times in a single session

查看:84
本文介绍了可移植地在一个会话中多次打开标准输入的句柄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

main = do
         putStrLn "4917 Microprocessor\nEnter the Machine Code to be run: "
         inp <- getContents
         putStrLn "The output of the Program is:"
         fState <- ((runStateT _4917) . construct . parse) inp
         args <- getArgs
         if elem "-v" args then putStrLn ("\nFinal state was: " ++ (show . snd) fState) else return ()
         putStrLn "\n================================ RESTART ================================"
         main
        where parse xs = array (0,15) $
                         zip [0..15] $
                         take 16 $
                         map ((makeArbInt 4) . read) (words (filter ((/=)'.') xs)) ++ repeat (makeArbInt 4 0)
              construct xs = Program xs z z z z 0 False
              z = (makeArbInt 4 0)

还有更多,但这是相关的部分.基本上,第3行需要多次评估,但是getContents关闭了stdin句柄:

There's more but this is the relevant part. Basically line 3 needs to be evaluated multiple times but getContents is closing the stdin handle:

4917: <stdin>: hGetContents: illegal operation (handle is closed)

是否可以重新打开手柄?还是某种防止getContents这样做的方法? (也许我发送的信号是错误的.我是通过Linux上的Ctrl-D EOF发送的.也许我应该使用EOT或其他方式?)

Is there a way to reopen the handle? Or some way of preventing getContents from doing that? (Maybe I'm sending the wrong signal. I'm sending over a Ctrl-D EOF on Linux. Maybe I should use EOT or something instead?)

我已经设法获得了想要的行为,但是它不会移植到Windows.

edit: I've managed to get the desired behaviour but it won't port to windows.

mystdin <- openFile "/dev/tty" ReadMode
inp <- hGetContents mystdin

新问题:是否有一种通用的方法来便携式打开stdin的句柄?

New question: is there a generic way to portably open a handle to stdin?

推荐答案

要打开可移动到stdin的句柄,请在现有stdio句柄上使用hDuplicate函数以获取一个新句柄:

To open a handle to stdin portably, use hDuplicate function on the existing stdio handle to get a new one:

mystdin <- hDuplicate stdin
inp <- hGetContents mystdin

确保不要关闭原始的stdin,以便您可以根据需要进行更多重复. (我不确定这是不是很好的Haskell风格)

Make sure never to close the original stdin, so that you can make more duplicates as appropriate. (I'm not sure if this is good Haskell style)

这篇关于可移植地在一个会话中多次打开标准输入的句柄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆