forked from u-root/u-root
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnohup.go
85 lines (69 loc) · 1.59 KB
/
nohup.go
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright 2024 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// nohup – invoke a utility immune to hangups.
//
// Synopsis:
//
// nohup <command> [args...]
package main
import (
"errors"
"fmt"
"log"
"os"
"os/exec"
"os/signal"
"syscall"
"golang.org/x/term"
)
var (
errUsage = fmt.Errorf("nohup <command> [args...]")
errStart = fmt.Errorf("failed to start")
errFinish = fmt.Errorf("finished with error")
)
func main() {
if err := run(os.Args); err != nil {
if errors.Is(err, errUsage) {
fmt.Fprintf(os.Stderr, "Usage: %v\n", errUsage)
os.Exit(127)
}
log.Fatalf("nohup: %v", err)
}
}
func run(args []string) error {
if len(args) < 2 {
return errUsage
}
signal.Ignore(syscall.SIGHUP)
cmdName := args[1]
cmdArgs := args[2:]
cmd := exec.Command(cmdName, cmdArgs...)
stdoutIsTerminal := term.IsTerminal(int(os.Stdout.Fd()))
stderrIsTerminal := term.IsTerminal(int(os.Stderr.Fd()))
if stdoutIsTerminal {
outputFile, err := os.OpenFile("nohup.out", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
return fmt.Errorf("error opening file: %w", err)
}
defer outputFile.Close()
cmd.Stdout = outputFile
if stderrIsTerminal {
cmd.Stderr = outputFile
} else {
cmd.Stderr = os.Stderr
}
} else {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
}
err := cmd.Start()
if err != nil {
return fmt.Errorf("%s: %w: %v", cmdName, errStart, err)
}
err = cmd.Wait()
if err != nil {
return fmt.Errorf("%s: %w: %v", cmdName, errFinish, err)
}
return nil
}