cmd_fg.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "strconv"
  6. "syscall"
  7. )
  8. // 前台执行job
  9. func cmd_fg(fields []string, stdin *os.File, stdout *os.File, stderr *os.File) {
  10. if len(fields) == 1 { // 如果没有指定job,则选编号最小的
  11. if len(jobs) == 0 { // 如果没有job
  12. panic("fg: no current job") // 则提示错误
  13. }
  14. for i := range jobs {
  15. fields = append(fields, "%"+strconv.Itoa(i))
  16. break
  17. }
  18. }
  19. for _, jid := range fields[1:] { // 遍历参数
  20. id, err := strconv.Atoi(jid[1:]) // 字符串转数字
  21. if err != nil {
  22. panic("fg: job not found: " + jid)
  23. }
  24. _, ok := jobs[id] // 是否有指定编号的job
  25. if !ok {
  26. panic("fg: %" + jid[1:] + ": no such job")
  27. }
  28. cur = job{jobs[id].wait, "running", jobs[id].work, jobs[id].cmd} // 前台执行
  29. delete(jobs, id) // 删除job
  30. cur.cmd.Process.Signal(syscall.SIGCONT) // 向进程发送SIGCONT信号,继续执行
  31. fmt.Fprintf(stdout, "[%d] %d continued\t%s\n", id, cur.cmd.Process.Pid, cur.work)
  32. term = make(chan bool) // 初始化停止信号管道
  33. <-term // 等待接收信号,实现前台执行
  34. close(term) // 关闭停止管道
  35. cur.cmd = nil // 前台没有在执行命令
  36. }
  37. }