github.com/rsc/go@v0.0.0-20150416155037-e040fd465409/src/os/exec/exec_test.go (about) 1 // Copyright 2009 The Go 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 5 // Use an external test to avoid os/exec -> net/http -> crypto/x509 -> os/exec 6 // circular dependency on non-cgo darwin. 7 8 package exec_test 9 10 import ( 11 "bufio" 12 "bytes" 13 "fmt" 14 "io" 15 "io/ioutil" 16 "log" 17 "net" 18 "net/http" 19 "net/http/httptest" 20 "os" 21 "os/exec" 22 "path/filepath" 23 "runtime" 24 "strconv" 25 "strings" 26 "testing" 27 "time" 28 ) 29 30 // iOS cannot fork 31 var iOS = runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64") 32 33 func helperCommand(t *testing.T, s ...string) *exec.Cmd { 34 if runtime.GOOS == "nacl" || iOS { 35 t.Skipf("skipping on %s/%s, cannot fork", runtime.GOOS, runtime.GOARCH) 36 } 37 cs := []string{"-test.run=TestHelperProcess", "--"} 38 cs = append(cs, s...) 39 cmd := exec.Command(os.Args[0], cs...) 40 cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} 41 return cmd 42 } 43 44 func TestEcho(t *testing.T) { 45 bs, err := helperCommand(t, "echo", "foo bar", "baz").Output() 46 if err != nil { 47 t.Errorf("echo: %v", err) 48 } 49 if g, e := string(bs), "foo bar baz\n"; g != e { 50 t.Errorf("echo: want %q, got %q", e, g) 51 } 52 } 53 54 func TestCommandRelativeName(t *testing.T) { 55 if iOS { 56 t.Skip("skipping on darwin/%s, cannot fork", runtime.GOARCH) 57 } 58 59 // Run our own binary as a relative path 60 // (e.g. "_test/exec.test") our parent directory. 61 base := filepath.Base(os.Args[0]) // "exec.test" 62 dir := filepath.Dir(os.Args[0]) // "/tmp/go-buildNNNN/os/exec/_test" 63 if dir == "." { 64 t.Skip("skipping; running test at root somehow") 65 } 66 parentDir := filepath.Dir(dir) // "/tmp/go-buildNNNN/os/exec" 67 dirBase := filepath.Base(dir) // "_test" 68 if dirBase == "." { 69 t.Skipf("skipping; unexpected shallow dir of %q", dir) 70 } 71 72 cmd := exec.Command(filepath.Join(dirBase, base), "-test.run=TestHelperProcess", "--", "echo", "foo") 73 cmd.Dir = parentDir 74 cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} 75 76 out, err := cmd.Output() 77 if err != nil { 78 t.Errorf("echo: %v", err) 79 } 80 if g, e := string(out), "foo\n"; g != e { 81 t.Errorf("echo: want %q, got %q", e, g) 82 } 83 } 84 85 func TestCatStdin(t *testing.T) { 86 // Cat, testing stdin and stdout. 87 input := "Input string\nLine 2" 88 p := helperCommand(t, "cat") 89 p.Stdin = strings.NewReader(input) 90 bs, err := p.Output() 91 if err != nil { 92 t.Errorf("cat: %v", err) 93 } 94 s := string(bs) 95 if s != input { 96 t.Errorf("cat: want %q, got %q", input, s) 97 } 98 } 99 100 func TestCatGoodAndBadFile(t *testing.T) { 101 // Testing combined output and error values. 102 bs, err := helperCommand(t, "cat", "/bogus/file.foo", "exec_test.go").CombinedOutput() 103 if _, ok := err.(*exec.ExitError); !ok { 104 t.Errorf("expected *exec.ExitError from cat combined; got %T: %v", err, err) 105 } 106 s := string(bs) 107 sp := strings.SplitN(s, "\n", 2) 108 if len(sp) != 2 { 109 t.Fatalf("expected two lines from cat; got %q", s) 110 } 111 errLine, body := sp[0], sp[1] 112 if !strings.HasPrefix(errLine, "Error: open /bogus/file.foo") { 113 t.Errorf("expected stderr to complain about file; got %q", errLine) 114 } 115 if !strings.Contains(body, "func TestHelperProcess(t *testing.T)") { 116 t.Errorf("expected test code; got %q (len %d)", body, len(body)) 117 } 118 } 119 120 func TestNoExistBinary(t *testing.T) { 121 // Can't run a non-existent binary 122 err := exec.Command("/no-exist-binary").Run() 123 if err == nil { 124 t.Error("expected error from /no-exist-binary") 125 } 126 } 127 128 func TestExitStatus(t *testing.T) { 129 // Test that exit values are returned correctly 130 cmd := helperCommand(t, "exit", "42") 131 err := cmd.Run() 132 want := "exit status 42" 133 switch runtime.GOOS { 134 case "plan9": 135 want = fmt.Sprintf("exit status: '%s %d: 42'", filepath.Base(cmd.Path), cmd.ProcessState.Pid()) 136 } 137 if werr, ok := err.(*exec.ExitError); ok { 138 if s := werr.Error(); s != want { 139 t.Errorf("from exit 42 got exit %q, want %q", s, want) 140 } 141 } else { 142 t.Fatalf("expected *exec.ExitError from exit 42; got %T: %v", err, err) 143 } 144 } 145 146 func TestPipes(t *testing.T) { 147 check := func(what string, err error) { 148 if err != nil { 149 t.Fatalf("%s: %v", what, err) 150 } 151 } 152 // Cat, testing stdin and stdout. 153 c := helperCommand(t, "pipetest") 154 stdin, err := c.StdinPipe() 155 check("StdinPipe", err) 156 stdout, err := c.StdoutPipe() 157 check("StdoutPipe", err) 158 stderr, err := c.StderrPipe() 159 check("StderrPipe", err) 160 161 outbr := bufio.NewReader(stdout) 162 errbr := bufio.NewReader(stderr) 163 line := func(what string, br *bufio.Reader) string { 164 line, _, err := br.ReadLine() 165 if err != nil { 166 t.Fatalf("%s: %v", what, err) 167 } 168 return string(line) 169 } 170 171 err = c.Start() 172 check("Start", err) 173 174 _, err = stdin.Write([]byte("O:I am output\n")) 175 check("first stdin Write", err) 176 if g, e := line("first output line", outbr), "O:I am output"; g != e { 177 t.Errorf("got %q, want %q", g, e) 178 } 179 180 _, err = stdin.Write([]byte("E:I am error\n")) 181 check("second stdin Write", err) 182 if g, e := line("first error line", errbr), "E:I am error"; g != e { 183 t.Errorf("got %q, want %q", g, e) 184 } 185 186 _, err = stdin.Write([]byte("O:I am output2\n")) 187 check("third stdin Write 3", err) 188 if g, e := line("second output line", outbr), "O:I am output2"; g != e { 189 t.Errorf("got %q, want %q", g, e) 190 } 191 192 stdin.Close() 193 err = c.Wait() 194 check("Wait", err) 195 } 196 197 const stdinCloseTestString = "Some test string." 198 199 // Issue 6270. 200 func TestStdinClose(t *testing.T) { 201 check := func(what string, err error) { 202 if err != nil { 203 t.Fatalf("%s: %v", what, err) 204 } 205 } 206 cmd := helperCommand(t, "stdinClose") 207 stdin, err := cmd.StdinPipe() 208 check("StdinPipe", err) 209 // Check that we can access methods of the underlying os.File.` 210 if _, ok := stdin.(interface { 211 Fd() uintptr 212 }); !ok { 213 t.Error("can't access methods of underlying *os.File") 214 } 215 check("Start", cmd.Start()) 216 go func() { 217 _, err := io.Copy(stdin, strings.NewReader(stdinCloseTestString)) 218 check("Copy", err) 219 // Before the fix, this next line would race with cmd.Wait. 220 check("Close", stdin.Close()) 221 }() 222 check("Wait", cmd.Wait()) 223 } 224 225 // Issue 5071 226 func TestPipeLookPathLeak(t *testing.T) { 227 fd0, lsof0 := numOpenFDS(t) 228 for i := 0; i < 4; i++ { 229 cmd := exec.Command("something-that-does-not-exist-binary") 230 cmd.StdoutPipe() 231 cmd.StderrPipe() 232 cmd.StdinPipe() 233 if err := cmd.Run(); err == nil { 234 t.Fatal("unexpected success") 235 } 236 } 237 for triesLeft := 3; triesLeft >= 0; triesLeft-- { 238 open, lsof := numOpenFDS(t) 239 fdGrowth := open - fd0 240 if fdGrowth > 2 { 241 if triesLeft > 0 { 242 // Work around what appears to be a race with Linux's 243 // proc filesystem (as used by lsof). It seems to only 244 // be eventually consistent. Give it awhile to settle. 245 // See golang.org/issue/7808 246 time.Sleep(100 * time.Millisecond) 247 continue 248 } 249 t.Errorf("leaked %d fds; want ~0; have:\n%s\noriginally:\n%s", fdGrowth, lsof, lsof0) 250 } 251 break 252 } 253 } 254 255 func numOpenFDS(t *testing.T) (n int, lsof []byte) { 256 if runtime.GOOS == "android" { 257 // Android's stock lsof does not obey the -p option, 258 // so extra filtering is needed. (golang.org/issue/10206) 259 return numOpenFDsAndroid(t) 260 } 261 262 lsof, err := exec.Command("lsof", "-b", "-n", "-p", strconv.Itoa(os.Getpid())).Output() 263 if err != nil { 264 t.Skip("skipping test; error finding or running lsof") 265 } 266 return bytes.Count(lsof, []byte("\n")), lsof 267 } 268 269 func numOpenFDsAndroid(t *testing.T) (n int, lsof []byte) { 270 raw, err := exec.Command("lsof").Output() 271 if err != nil { 272 t.Skip("skipping test; error finding or running lsof") 273 } 274 275 // First find the PID column index by parsing the first line, and 276 // select lines containing pid in the column. 277 pid := []byte(strconv.Itoa(os.Getpid())) 278 pidCol := -1 279 280 s := bufio.NewScanner(bytes.NewReader(raw)) 281 for s.Scan() { 282 line := s.Bytes() 283 fields := bytes.Fields(line) 284 if pidCol < 0 { 285 for i, v := range fields { 286 if bytes.Equal(v, []byte("PID")) { 287 pidCol = i 288 break 289 } 290 } 291 lsof = append(lsof, line...) 292 continue 293 } 294 if bytes.Equal(fields[pidCol], pid) { 295 lsof = append(lsof, '\n') 296 lsof = append(lsof, line...) 297 } 298 } 299 if pidCol < 0 { 300 t.Fatal("error processing lsof output: unexpected header format") 301 } 302 if err := s.Err(); err != nil { 303 t.Fatalf("error processing lsof output: %v", err) 304 } 305 return bytes.Count(lsof, []byte("\n")), lsof 306 } 307 308 var testedAlreadyLeaked = false 309 310 // basefds returns the number of expected file descriptors 311 // to be present in a process at start. 312 func basefds() uintptr { 313 return os.Stderr.Fd() + 1 314 } 315 316 func closeUnexpectedFds(t *testing.T, m string) { 317 for fd := basefds(); fd <= 101; fd++ { 318 err := os.NewFile(fd, "").Close() 319 if err == nil { 320 t.Logf("%s: Something already leaked - closed fd %d", m, fd) 321 } 322 } 323 } 324 325 func TestExtraFilesFDShuffle(t *testing.T) { 326 t.Skip("flaky test; see http://golang.org/issue/5780") 327 switch runtime.GOOS { 328 case "darwin": 329 // TODO(cnicolaou): http://golang.org/issue/2603 330 // leads to leaked file descriptors in this test when it's 331 // run from a builder. 332 closeUnexpectedFds(t, "TestExtraFilesFDShuffle") 333 case "netbsd": 334 // http://golang.org/issue/3955 335 closeUnexpectedFds(t, "TestExtraFilesFDShuffle") 336 case "windows": 337 t.Skip("no operating system support; skipping") 338 } 339 340 // syscall.StartProcess maps all the FDs passed to it in 341 // ProcAttr.Files (the concatenation of stdin,stdout,stderr and 342 // ExtraFiles) into consecutive FDs in the child, that is: 343 // Files{11, 12, 6, 7, 9, 3} should result in the file 344 // represented by FD 11 in the parent being made available as 0 345 // in the child, 12 as 1, etc. 346 // 347 // We want to test that FDs in the child do not get overwritten 348 // by one another as this shuffle occurs. The original implementation 349 // was buggy in that in some data dependent cases it would ovewrite 350 // stderr in the child with one of the ExtraFile members. 351 // Testing for this case is difficult because it relies on using 352 // the same FD values as that case. In particular, an FD of 3 353 // must be at an index of 4 or higher in ProcAttr.Files and 354 // the FD of the write end of the Stderr pipe (as obtained by 355 // StderrPipe()) must be the same as the size of ProcAttr.Files; 356 // therefore we test that the read end of this pipe (which is what 357 // is returned to the parent by StderrPipe() being one less than 358 // the size of ProcAttr.Files, i.e. 3+len(cmd.ExtraFiles). 359 // 360 // Moving this test case around within the overall tests may 361 // affect the FDs obtained and hence the checks to catch these cases. 362 npipes := 2 363 c := helperCommand(t, "extraFilesAndPipes", strconv.Itoa(npipes+1)) 364 rd, wr, _ := os.Pipe() 365 defer rd.Close() 366 if rd.Fd() != 3 { 367 t.Errorf("bad test value for test pipe: fd %d", rd.Fd()) 368 } 369 stderr, _ := c.StderrPipe() 370 wr.WriteString("_LAST") 371 wr.Close() 372 373 pipes := make([]struct { 374 r, w *os.File 375 }, npipes) 376 data := []string{"a", "b"} 377 378 for i := 0; i < npipes; i++ { 379 r, w, err := os.Pipe() 380 if err != nil { 381 t.Fatalf("unexpected error creating pipe: %s", err) 382 } 383 pipes[i].r = r 384 pipes[i].w = w 385 w.WriteString(data[i]) 386 c.ExtraFiles = append(c.ExtraFiles, pipes[i].r) 387 defer func() { 388 r.Close() 389 w.Close() 390 }() 391 } 392 // Put fd 3 at the end. 393 c.ExtraFiles = append(c.ExtraFiles, rd) 394 395 stderrFd := int(stderr.(*os.File).Fd()) 396 if stderrFd != ((len(c.ExtraFiles) + 3) - 1) { 397 t.Errorf("bad test value for stderr pipe") 398 } 399 400 expected := "child: " + strings.Join(data, "") + "_LAST" 401 402 err := c.Start() 403 if err != nil { 404 t.Fatalf("Run: %v", err) 405 } 406 ch := make(chan string, 1) 407 go func(ch chan string) { 408 buf := make([]byte, 512) 409 n, err := stderr.Read(buf) 410 if err != nil { 411 t.Fatalf("Read: %s", err) 412 ch <- err.Error() 413 } else { 414 ch <- string(buf[:n]) 415 } 416 close(ch) 417 }(ch) 418 select { 419 case m := <-ch: 420 if m != expected { 421 t.Errorf("Read: '%s' not '%s'", m, expected) 422 } 423 case <-time.After(5 * time.Second): 424 t.Errorf("Read timedout") 425 } 426 c.Wait() 427 } 428 429 func TestExtraFiles(t *testing.T) { 430 switch runtime.GOOS { 431 case "nacl", "windows": 432 t.Skipf("skipping test on %q", runtime.GOOS) 433 } 434 if iOS { 435 t.Skipf("skipping test on %s/%s, cannot fork", runtime.GOOS, runtime.GOARCH) 436 } 437 438 // Ensure that file descriptors have not already been leaked into 439 // our environment. 440 if !testedAlreadyLeaked { 441 testedAlreadyLeaked = true 442 closeUnexpectedFds(t, "TestExtraFiles") 443 } 444 445 // Force network usage, to verify the epoll (or whatever) fd 446 // doesn't leak to the child, 447 ln, err := net.Listen("tcp", "127.0.0.1:0") 448 if err != nil { 449 t.Fatal(err) 450 } 451 defer ln.Close() 452 453 // Make sure duplicated fds don't leak to the child. 454 f, err := ln.(*net.TCPListener).File() 455 if err != nil { 456 t.Fatal(err) 457 } 458 defer f.Close() 459 ln2, err := net.FileListener(f) 460 if err != nil { 461 t.Fatal(err) 462 } 463 defer ln2.Close() 464 465 // Force TLS root certs to be loaded (which might involve 466 // cgo), to make sure none of that potential C code leaks fds. 467 ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) 468 // quiet expected TLS handshake error "remote error: bad certificate" 469 ts.Config.ErrorLog = log.New(ioutil.Discard, "", 0) 470 ts.StartTLS() 471 defer ts.Close() 472 _, err = http.Get(ts.URL) 473 if err == nil { 474 t.Errorf("success trying to fetch %s; want an error", ts.URL) 475 } 476 477 tf, err := ioutil.TempFile("", "") 478 if err != nil { 479 t.Fatalf("TempFile: %v", err) 480 } 481 defer os.Remove(tf.Name()) 482 defer tf.Close() 483 484 const text = "Hello, fd 3!" 485 _, err = tf.Write([]byte(text)) 486 if err != nil { 487 t.Fatalf("Write: %v", err) 488 } 489 _, err = tf.Seek(0, os.SEEK_SET) 490 if err != nil { 491 t.Fatalf("Seek: %v", err) 492 } 493 494 c := helperCommand(t, "read3") 495 var stdout, stderr bytes.Buffer 496 c.Stdout = &stdout 497 c.Stderr = &stderr 498 c.ExtraFiles = []*os.File{tf} 499 err = c.Run() 500 if err != nil { 501 t.Fatalf("Run: %v; stdout %q, stderr %q", err, stdout.Bytes(), stderr.Bytes()) 502 } 503 if stdout.String() != text { 504 t.Errorf("got stdout %q, stderr %q; want %q on stdout", stdout.String(), stderr.String(), text) 505 } 506 } 507 508 func TestExtraFilesRace(t *testing.T) { 509 if runtime.GOOS == "windows" { 510 t.Skip("no operating system support; skipping") 511 } 512 listen := func() net.Listener { 513 ln, err := net.Listen("tcp", "127.0.0.1:0") 514 if err != nil { 515 t.Fatal(err) 516 } 517 return ln 518 } 519 listenerFile := func(ln net.Listener) *os.File { 520 f, err := ln.(*net.TCPListener).File() 521 if err != nil { 522 t.Fatal(err) 523 } 524 return f 525 } 526 runCommand := func(c *exec.Cmd, out chan<- string) { 527 bout, err := c.CombinedOutput() 528 if err != nil { 529 out <- "ERROR:" + err.Error() 530 } else { 531 out <- string(bout) 532 } 533 } 534 535 for i := 0; i < 10; i++ { 536 la := listen() 537 ca := helperCommand(t, "describefiles") 538 ca.ExtraFiles = []*os.File{listenerFile(la)} 539 lb := listen() 540 cb := helperCommand(t, "describefiles") 541 cb.ExtraFiles = []*os.File{listenerFile(lb)} 542 ares := make(chan string) 543 bres := make(chan string) 544 go runCommand(ca, ares) 545 go runCommand(cb, bres) 546 if got, want := <-ares, fmt.Sprintf("fd3: listener %s\n", la.Addr()); got != want { 547 t.Errorf("iteration %d, process A got:\n%s\nwant:\n%s\n", i, got, want) 548 } 549 if got, want := <-bres, fmt.Sprintf("fd3: listener %s\n", lb.Addr()); got != want { 550 t.Errorf("iteration %d, process B got:\n%s\nwant:\n%s\n", i, got, want) 551 } 552 la.Close() 553 lb.Close() 554 for _, f := range ca.ExtraFiles { 555 f.Close() 556 } 557 for _, f := range cb.ExtraFiles { 558 f.Close() 559 } 560 561 } 562 } 563 564 // TestHelperProcess isn't a real test. It's used as a helper process 565 // for TestParameterRun. 566 func TestHelperProcess(*testing.T) { 567 if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" { 568 return 569 } 570 defer os.Exit(0) 571 572 // Determine which command to use to display open files. 573 ofcmd := "lsof" 574 switch runtime.GOOS { 575 case "dragonfly", "freebsd", "netbsd", "openbsd": 576 ofcmd = "fstat" 577 case "plan9": 578 ofcmd = "/bin/cat" 579 } 580 581 args := os.Args 582 for len(args) > 0 { 583 if args[0] == "--" { 584 args = args[1:] 585 break 586 } 587 args = args[1:] 588 } 589 if len(args) == 0 { 590 fmt.Fprintf(os.Stderr, "No command\n") 591 os.Exit(2) 592 } 593 594 cmd, args := args[0], args[1:] 595 switch cmd { 596 case "echo": 597 iargs := []interface{}{} 598 for _, s := range args { 599 iargs = append(iargs, s) 600 } 601 fmt.Println(iargs...) 602 case "cat": 603 if len(args) == 0 { 604 io.Copy(os.Stdout, os.Stdin) 605 return 606 } 607 exit := 0 608 for _, fn := range args { 609 f, err := os.Open(fn) 610 if err != nil { 611 fmt.Fprintf(os.Stderr, "Error: %v\n", err) 612 exit = 2 613 } else { 614 defer f.Close() 615 io.Copy(os.Stdout, f) 616 } 617 } 618 os.Exit(exit) 619 case "pipetest": 620 bufr := bufio.NewReader(os.Stdin) 621 for { 622 line, _, err := bufr.ReadLine() 623 if err == io.EOF { 624 break 625 } else if err != nil { 626 os.Exit(1) 627 } 628 if bytes.HasPrefix(line, []byte("O:")) { 629 os.Stdout.Write(line) 630 os.Stdout.Write([]byte{'\n'}) 631 } else if bytes.HasPrefix(line, []byte("E:")) { 632 os.Stderr.Write(line) 633 os.Stderr.Write([]byte{'\n'}) 634 } else { 635 os.Exit(1) 636 } 637 } 638 case "stdinClose": 639 b, err := ioutil.ReadAll(os.Stdin) 640 if err != nil { 641 fmt.Fprintf(os.Stderr, "Error: %v\n", err) 642 os.Exit(1) 643 } 644 if s := string(b); s != stdinCloseTestString { 645 fmt.Fprintf(os.Stderr, "Error: Read %q, want %q", s, stdinCloseTestString) 646 os.Exit(1) 647 } 648 os.Exit(0) 649 case "read3": // read fd 3 650 fd3 := os.NewFile(3, "fd3") 651 bs, err := ioutil.ReadAll(fd3) 652 if err != nil { 653 fmt.Printf("ReadAll from fd 3: %v", err) 654 os.Exit(1) 655 } 656 switch runtime.GOOS { 657 case "dragonfly": 658 // TODO(jsing): Determine why DragonFly is leaking 659 // file descriptors... 660 case "darwin": 661 // TODO(bradfitz): broken? Sometimes. 662 // http://golang.org/issue/2603 663 // Skip this additional part of the test for now. 664 case "netbsd": 665 // TODO(jsing): This currently fails on NetBSD due to 666 // the cloned file descriptors that result from opening 667 // /dev/urandom. 668 // http://golang.org/issue/3955 669 case "plan9": 670 // TODO(0intro): Determine why Plan 9 is leaking 671 // file descriptors. 672 // http://golang.org/issue/7118 673 case "solaris": 674 // TODO(aram): This fails on Solaris because libc opens 675 // its own files, as it sees fit. Darwin does the same, 676 // see: http://golang.org/issue/2603 677 default: 678 // Now verify that there are no other open fds. 679 var files []*os.File 680 for wantfd := basefds() + 1; wantfd <= 100; wantfd++ { 681 f, err := os.Open(os.Args[0]) 682 if err != nil { 683 fmt.Printf("error opening file with expected fd %d: %v", wantfd, err) 684 os.Exit(1) 685 } 686 if got := f.Fd(); got != wantfd { 687 fmt.Printf("leaked parent file. fd = %d; want %d\n", got, wantfd) 688 var args []string 689 switch runtime.GOOS { 690 case "plan9": 691 args = []string{fmt.Sprintf("/proc/%d/fd", os.Getpid())} 692 default: 693 args = []string{"-p", fmt.Sprint(os.Getpid())} 694 } 695 out, _ := exec.Command(ofcmd, args...).CombinedOutput() 696 fmt.Print(string(out)) 697 os.Exit(1) 698 } 699 files = append(files, f) 700 } 701 for _, f := range files { 702 f.Close() 703 } 704 } 705 // Referring to fd3 here ensures that it is not 706 // garbage collected, and therefore closed, while 707 // executing the wantfd loop above. It doesn't matter 708 // what we do with fd3 as long as we refer to it; 709 // closing it is the easy choice. 710 fd3.Close() 711 os.Stdout.Write(bs) 712 case "exit": 713 n, _ := strconv.Atoi(args[0]) 714 os.Exit(n) 715 case "describefiles": 716 f := os.NewFile(3, fmt.Sprintf("fd3")) 717 ln, err := net.FileListener(f) 718 if err == nil { 719 fmt.Printf("fd3: listener %s\n", ln.Addr()) 720 ln.Close() 721 } 722 os.Exit(0) 723 case "extraFilesAndPipes": 724 n, _ := strconv.Atoi(args[0]) 725 pipes := make([]*os.File, n) 726 for i := 0; i < n; i++ { 727 pipes[i] = os.NewFile(uintptr(3+i), strconv.Itoa(i)) 728 } 729 response := "" 730 for i, r := range pipes { 731 ch := make(chan string, 1) 732 go func(c chan string) { 733 buf := make([]byte, 10) 734 n, err := r.Read(buf) 735 if err != nil { 736 fmt.Fprintf(os.Stderr, "Child: read error: %v on pipe %d\n", err, i) 737 os.Exit(1) 738 } 739 c <- string(buf[:n]) 740 close(c) 741 }(ch) 742 select { 743 case m := <-ch: 744 response = response + m 745 case <-time.After(5 * time.Second): 746 fmt.Fprintf(os.Stderr, "Child: Timeout reading from pipe: %d\n", i) 747 os.Exit(1) 748 } 749 } 750 fmt.Fprintf(os.Stderr, "child: %s", response) 751 os.Exit(0) 752 case "exec": 753 cmd := exec.Command(args[1]) 754 cmd.Dir = args[0] 755 output, err := cmd.CombinedOutput() 756 if err != nil { 757 fmt.Fprintf(os.Stderr, "Child: %s %s", err, string(output)) 758 os.Exit(1) 759 } 760 fmt.Printf("%s", string(output)) 761 os.Exit(0) 762 case "lookpath": 763 p, err := exec.LookPath(args[0]) 764 if err != nil { 765 fmt.Fprintf(os.Stderr, "LookPath failed: %v\n", err) 766 os.Exit(1) 767 } 768 fmt.Print(p) 769 os.Exit(0) 770 default: 771 fmt.Fprintf(os.Stderr, "Unknown command %q\n", cmd) 772 os.Exit(2) 773 } 774 }