elvish/pkg/eval/builtin_fn_cmd_unix.go

102 lines
2.0 KiB
Go
Raw Normal View History

2017-12-08 08:45:10 +08:00
// +build !windows,!plan9
package eval
import (
2019-04-19 05:15:34 +08:00
"errors"
"os"
"os/exec"
"strconv"
"syscall"
2019-12-24 04:00:59 +08:00
"github.com/elves/elvish/pkg/eval/vals"
"github.com/elves/elvish/pkg/sys"
"github.com/elves/elvish/pkg/util"
)
2019-04-19 05:15:34 +08:00
// ErrNotInSameProcessGroup is thrown when the process IDs passed to fg are not
// in the same process group.
var ErrNotInSameProcessGroup = errors.New("not in the same process group")
func execFn(fm *Frame, args ...interface{}) error {
var argstrings []string
if len(args) == 0 {
argstrings = []string{"elvish"}
} else {
argstrings = make([]string, len(args))
for i, a := range args {
2018-02-15 17:14:05 +08:00
argstrings[i] = vals.ToString(a)
}
}
var err error
argstrings[0], err = exec.LookPath(argstrings[0])
if err != nil {
return err
}
preExit(fm)
decSHLVL()
return syscall.Exec(argstrings[0], argstrings, os.Environ())
}
// Decrements $E:SHLVL. Called from execFn to ensure that $E:SHLVL remains the
// same in the new command.
func decSHLVL() {
i, err := strconv.Atoi(os.Getenv(util.EnvSHLVL))
if err != nil {
return
}
os.Setenv(util.EnvSHLVL, strconv.Itoa(i-1))
}
func fg(pids ...int) error {
if len(pids) == 0 {
return ErrArgs
}
var thepgid int
for i, pid := range pids {
pgid, err := syscall.Getpgid(pid)
if err != nil {
return err
}
if i == 0 {
thepgid = pgid
} else if pgid != thepgid {
2019-04-19 05:15:34 +08:00
return ErrNotInSameProcessGroup
}
}
err := sys.Tcsetpgrp(0, thepgid)
if err != nil {
return err
}
errors := make([]*Exception, len(pids))
for i, pid := range pids {
err := syscall.Kill(pid, syscall.SIGCONT)
if err != nil {
errors[i] = &Exception{err, nil}
}
}
for i, pid := range pids {
if errors[i] != nil {
continue
}
var ws syscall.WaitStatus
_, err = syscall.Wait4(pid, &ws, syscall.WUNTRACED, nil)
if err != nil {
errors[i] = &Exception{err, nil}
} else {
// TODO find command name
errors[i] = &Exception{NewExternalCmdExit(
"[pid "+strconv.Itoa(pid)+"]", ws, pid), nil}
}
}
return makePipelineError(errors)
}