[Haskell-cafe] System.Posix, forked processes and psuedo terminals on Linux

Erik de Castro Lopo mle+hs at mega-nerd.com
Sat Aug 21 01:47:27 EDT 2010


Hi all,

I've got a but it code below thats not quite working as I expect
it to. The basic idea is that it opens a master/slave pair of
pseudo terminals, forks a child process and then perform
bi-directional communication between the parent and the child
via the master/slave psuedo terminal.

The thing does really need to forkProcess because once the 
comms is working I want to exec another process in the child.
I also intend to dup the file descriptors so that stdin, stdout
and stderr all point to the slave's end of the pty.

The code below *almost* works. Its currently printing out:

    parent : Forked child was here!
    parent : Message from parent.
    Read 21 bytes

while I think it should print:

    parent : Forked child was here!
    parent : Read 21 bytes

Any clues on why 'Message from parent.' is also ending up on
stdout? This is ghc-6.12.1 on Debian Linux.

Cheers,
Erik

import System.Posix.IO
import System.Posix.Process
import System.Posix.Terminal
import System.Posix.Types

main :: IO ()
main
 = do	(master, slave) <- openPseudoTerminal
	_childId <- forkProcess $ forkedChild (master, slave)
	closeFd slave
	runParent master

runParent :: Fd -> IO ()
runParent fd
 = do	(str, _) <- fdRead fd 1024
	putStr $ "parent : " ++ str
	_ <- fdWrite fd "Message from parent.\n"
	(str2, _) <- fdRead fd 1024
	putStr $ "parent : " ++ str2

forkedChild :: (Fd, Fd) -> IO ()
forkedChild (master, fd)
 = do	closeFd master
	_ <- fdWrite fd "Forked child was here!\n"
	(_, count) <- fdRead fd 1024
	_ <- fdWrite fd $ "Read " ++ show count ++ " bytes\n"
	closeFd fd


-- 
----------------------------------------------------------------------
Erik de Castro Lopo
http://www.mega-nerd.com/


More information about the Haskell-Cafe mailing list