从createProcess外部获得的句柄中读取 [英] Reading from a handle obtained outside createProcess

查看:171
本文介绍了从createProcess外部获得的句柄中读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个进程,并通过我在 createProcess 函数之外提供的句柄与它进行通信:

  stdOutH < -  openFile(logDir stdout.log)ReadWriteMode 
hSetBuffering stdOutH LineBuffering
(_,_,_ ,ph)< - createProcess
(procsomeproc[]){std_out = UseHandle stdOutH
,std_err = UseHandle stdErrH
}
line< - hGetLine stdOutH
putStrLn $Got++行

someproc 进程向标准输出吐出一行,我想从产生它的进程读取它。然而,如果我尝试这样做,我会得到以下错误:
$ b hGetLine:非法操作(句柄已关闭)

我不明白为什么在创建的进程正在运行时关闭句柄。如果我使用 CreatePipe 而不是 UseHandle ,这是有效的,问题是我只想读第一行。但是这样做需要继续读取管道,否则在someproc

那么,有没有一种方法可以使用 system.process 来通过 stdOutH 在上面描述的方式?

解决方案

createProcess 的这种行为是记录在案:


请注意,通过
UseHandle构造函数为std_in,std_out或std_err提供的句柄将通过调用此函数来关闭。


文档建议使用 createProcess _ 函数。


I'm trying to create a process, and communicate with it via a handle that I provide outside the createProcess function:

stdOutH <- openFile (logDir </> "stdout.log") ReadWriteMode
hSetBuffering stdOutH LineBuffering
(_, _, _, ph) <- createProcess $
    (proc "someproc" []) { std_out = UseHandle stdOutH
                         , std_err = UseHandle stdErrH
                         }
line <- hGetLine stdOutH
putStrLn $ "Got " ++ line

The "someproc" process spits a line out to the standard output, and I want to read it from the process that spawned it. However if I try to do this I get the following error:

hGetLine: illegal operation (handle is closed)

What I don't understand is why the handle is closed while the created process is running. This works if I use CreatePipe instead of UseHandle, the problem is that I only want to read the first line. But doing this requires to keep on reading from the pipe, otherwise it gets full after a certain amount of output by "someproc".

So, is there a way to use system.process to communicate two processes via stdOutH in the way described above?

解决方案

This behavior of createProcess is documented:

Note that Handles provided for std_in, std_out, or std_err via the UseHandle constructor will be closed by calling this function.

Documentation suggests to use createProcess_ function instead.

这篇关于从createProcess外部获得的句柄中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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