Wolfe
Wolfe

Reputation: 107

Haskell - Using the handle created from createProcess and CreatePipe to pipe into StdStream

I currently have this code:

main :: IO ()                                                                       
main = do                                                                           
    (_, Just so, _, _)  <- createProcess (proc "ls" ["."]) { std_out = CreatePipe } 
    _ <- createProcess (proc "sort" []) { std_in = so }                             
    print "foo"     

The error I'm getting is:

 Couldn't match expected type ‘StdStream’                 
         with actual type ‘GHC.IO.Handle.Types.Handle’
 In the ‘std_in’ field of a record                        
 In the first argument of ‘createProcess’, namely         
   ‘(proc "sort" []) {std_in = so}’                       
 In a stmt of a 'do' block:                               
   _ <- createProcess ((proc "sort" []) {std_in = so})    

I'm trying to pipe the output from the ls process into the sort process however the CreatePipe returns a Handle pair and std_in expects a StdStream.

How would I go about converting the handle into a stdstream.

Thanks!

Upvotes: 4

Views: 576

Answers (1)

K. A. Buhr
K. A. Buhr

Reputation: 50929

StdStream has a UseHandle constructor that will perform the conversion, so adjust your code to read:

_ <- createProcess (proc "sort" []) { std_in = UseHandle so }

and it'll run, printing a sorted directory listing.

However, if you want "foo" to be printed after the processes complete, you need to wait on both processes first. (You want to do this anyway, or you'll have a bunch of "zombie" processes hanging around until Haskell terminates.) Adjust your code to read:

main = do                                                                         
    (_, Just so, _, ph1)  <- createProcess (proc "ls" ["."])
                               { std_out = CreatePipe } 
    (_, _, _, ph2) <- createProcess (proc "sort" []) { std_in = UseHandle so }
    waitForProcess ph1
    waitForProcess ph2
    print "foo"

and you should be good to go

Upvotes: 6

Related Questions