blob: 8b3113b1d79791be382128a320567ddfd5e591c0 [file] [log] [blame]
Jiri Simsad7616c92015-03-24 23:44:30 -07001// Copyright 2015 The Vanadium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
Cosmos Nicolaou90610bd2014-12-02 22:31:04 -08005package modules_test
6
7import (
8 "fmt"
9 "io"
10 "os"
11
Cosmos Nicolaou1381f8a2015-03-13 09:40:34 -070012 "v.io/x/ref/test"
13 "v.io/x/ref/test/modules"
Cosmos Nicolaou90610bd2014-12-02 22:31:04 -080014)
15
16func init() {
17 modules.RegisterChild("echo", "<args>...", echo)
18}
19
20func echo(stdin io.Reader, stdout, stderr io.Writer, env map[string]string, args ...string) error {
21 for i, a := range args {
22 fmt.Fprintf(stdout, "%d: %s\n", i, a)
23 }
24 return nil
25}
26
27func ExampleDispatch() {
Cosmos Nicolaou1381f8a2015-03-13 09:40:34 -070028 ctx, shutdown := test.InitForTest()
Suharsh Sivakumar19fbf992015-01-23 11:02:27 -080029 defer shutdown()
Cosmos Nicolaou42a17362015-03-10 16:40:18 -070030 if modules.IsModulesChildProcess() {
Cosmos Nicolaou90610bd2014-12-02 22:31:04 -080031 // Child process. Dispatch will invoke the 'echo' command
32 if err := modules.Dispatch(); err != nil {
33 panic(fmt.Sprintf("unexpected error: %s", err))
34 }
35 return
36 }
37 // Parent process.
Cosmos Nicolaou9e909842015-03-17 11:58:59 -070038 sh, _ := modules.NewShell(ctx, nil, false, nil)
Cosmos Nicolaou90610bd2014-12-02 22:31:04 -080039 defer sh.Cleanup(nil, nil)
40 h, _ := sh.Start("echo", nil, "a", "b")
41 h.Shutdown(os.Stdout, os.Stderr)
42 // Output:
Suharsh Sivakumar9d17e4a2015-02-02 22:42:16 -080043 // 0: a
44 // 1: b
Cosmos Nicolaou90610bd2014-12-02 22:31:04 -080045}
46
47func ExampleDispatchAndExit() {
Cosmos Nicolaou1381f8a2015-03-13 09:40:34 -070048 ctx, shutdown := test.InitForTest()
Suharsh Sivakumar19fbf992015-01-23 11:02:27 -080049 defer shutdown()
Cosmos Nicolaou90610bd2014-12-02 22:31:04 -080050 // DispatchAndExit will call os.Exit(0) when executed within the child.
51 modules.DispatchAndExit()
Cosmos Nicolaou9e909842015-03-17 11:58:59 -070052 sh, _ := modules.NewShell(ctx, nil, false, nil)
Cosmos Nicolaou90610bd2014-12-02 22:31:04 -080053 defer sh.Cleanup(nil, nil)
54 h, _ := sh.Start("echo", nil, "c", "d")
55 h.Shutdown(os.Stdout, os.Stderr)
56 // Output:
Suharsh Sivakumar9d17e4a2015-02-02 22:42:16 -080057 // 0: c
58 // 1: d
Cosmos Nicolaou90610bd2014-12-02 22:31:04 -080059}