File: test-spawn.sml

package info (click to toggle)
mlton 20210117%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 58,464 kB
  • sloc: ansic: 27,682; sh: 4,455; asm: 3,569; lisp: 2,879; makefile: 2,347; perl: 1,169; python: 191; pascal: 68; javascript: 7
file content (64 lines) | stat: -rw-r--r-- 1,961 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
fun statusToString status =
   case status of
      Posix.Process.W_EXITED => "W_EXITED"
    | Posix.Process.W_EXITSTATUS w => concat ["W_EXITSTATUS ", Word8.toString w]
    | Posix.Process.W_SIGNALED s => 
         concat ["W_SIGNALED ", SysWord.toString (Posix.Signal.toWord s)]
    | Posix.Process.W_STOPPED s => 
         concat ["W_STOPPED ", SysWord.toString (Posix.Signal.toWord s)]

val cmd = CommandLine.name ()

fun stdout () =
   TextIO.output (TextIO.stdOut, "Hello world! [stdout]\n")
fun exit () = Posix.Process.exit 0wx7
fun diverge () = diverge ()

fun test () =
   let
      fun spawn arg =
         let
            val _ = TextIO.flushOut (TextIO.stdOut)
            val _ = TextIO.flushOut (TextIO.stdErr)
         in
            MLton.Process.spawn
            {path = cmd, args = [cmd, arg]}
         end
      fun waitpid pid =
         let
            val (pid', status) =
               Posix.Process.waitpid (Posix.Process.W_CHILD pid, [])
            val () =
               if pid <> pid'
                  then raise Fail "reap: pid <> pid'"
               else ()
         in
            status
         end
      fun kill (pid, signal) =
         Posix.Process.kill (Posix.Process.K_PROC pid, signal)
      fun doTest (arg, withPid) =
         let
            val _ = print (concat ["testing ", arg, "...\n"])
            val pid = spawn arg
            val () = withPid pid
            val status = waitpid pid
            val _ = print (concat ["exit_status: ", statusToString status, "\n"])
         in
            ()
         end
      fun doSimpleTest arg = doTest (arg, fn _ => ())
   in
      print "spawn test:\n"
      ; doSimpleTest "stdout"
      ; doSimpleTest "exit"
      ; doTest ("diverge", fn pid => kill (pid, Posix.Signal.kill))
   end

val _ =
   case CommandLine.arguments () of
      [] => test ()
    | ["stdout"] => stdout ()
    | ["exit"] => exit ()
    | ["diverge"] => diverge ()
    | _ => raise Match