Unix进程控制, fork

进程控制的例子

> import System.IO
> import System.Posix.Process (forkProcess, getProcessID)

获取当前进程号

> print_pid :: IO()
> print_pid = do
>   pid <- getProcessID
>   putStrLn ("I am the Parent, Pid=" ++ show pid)

unix中通过 fork 调用,可以产生一个子进程,这个调用对父进程返回子进程的pid,对子进程返回0。因此通过判断返回值可以确定自己是在父进程中还是在子进程中。然后子进程可以通过 exec 调用其他的命令替换掉自己。父进程可以通过 waitpid 等待子进程的退出。这是 shell 执行命令的一个基本过程。
forkProcess 参数是一个子进程的Action,返回值为子进程的pid

> parent pid = do
>   putStrLn "I am parent"
>   putStrLn ("The child pid=" ++ show pid)
>   putStrLn "---"

> child = do
>   putStrLn "I am child"
>   putStrLn "*****"

> test_fork :: IO()
> test_fork = do
>   putStrLn "Ready to fork a child process"
>   pid <- forkProcess child
>   parent pid


> main :: IO()
> main = do
>   print_pid
>   test_fork