こんにちは、kurumi-bioです。
第8回目のexecパッケージ(標準ライブラリー)の学習です。
環境
- Windows
OSバージョン:Windows11 Home 22H2
Go言語のバージョン:go version go1.20.3 windows/amd64 - Linux
OSバージョン:openSUSE Leap 15.4
Go言語のバージョン:go version go1.20.3 linux/amd64
CommandContext関数
func CommandContext(ctx context.Context, name string, arg ...string) *Cmd
[contextパッケージ] WithDeadline関数
func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)
[contextパッケージ] WithTimeout関数
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
◆テストコード
package main import ( "fmt" "time" ) func main() { fmt.Println("Start") time.Sleep(3 * time.Second) fmt.Println("End") }
◆テストコード
package main import ( "context" "fmt" "io" "os" "os/exec" "strconv" "time" ) func main() { if len(os.Args) != 2 { fmt.Fprintln(os.Stderr, "Timeoutまでの秒数を指定してください。") os.Exit(1) } i, _ := strconv.Atoi(os.Args[1]) t := time.Duration(i) ctx, cancel := context.WithTimeout(context.Background(), t*time.Second) defer cancel() c := exec.CommandContext(ctx, "./sleep.exe") o, e := c.StdoutPipe() if e != nil { fmt.Fprintf(os.Stderr, "%v\n", os.NewSyscallError("Cmd.StdoutPipe", e)) os.Exit(1) } if err := c.Start(); err != nil { fmt.Fprintf(os.Stderr, "%v\n", os.NewSyscallError("Cmd.Start", err)) os.Exit(1) } b, _ := io.ReadAll(o) fmt.Printf("%s\n", b) if err := c.Wait(); err != nil { fmt.Fprintf(os.Stderr, "%v\n", os.NewSyscallError("Cmd.Wait", err)) os.Exit(1) } }
◆実行結果(Windows)
◆実行結果(Windows)
◆実行結果(Linux)
◆テストコード
package main import ( "context" "fmt" "io" "os" "os/exec" "strconv" "time" ) func main() { const layout = "2006-01-02 15:04:05" if len(os.Args) != 2 { fmt.Fprintln(os.Stderr, "期限までの秒数を指定してください。") os.Exit(1) } i, _ := strconv.Atoi(os.Args[1]) t := time.Duration(i) n := time.Now() d := n.Add(t * time.Second) fmt.Printf("開始時刻:[%s]\n", n.Format(layout)) fmt.Printf("期限時刻:[%s]\n", d.Format(layout)) ctx, cancel := context.WithDeadline(context.Background(), d) defer cancel() c := exec.CommandContext(ctx, "./sleep.exe") o, e := c.StdoutPipe() if e != nil { fmt.Fprintf(os.Stderr, "%v\n", os.NewSyscallError("Cmd.StdoutPipe", e)) os.Exit(1) } if err := c.Start(); err != nil { fmt.Fprintf(os.Stderr, "%v\n", os.NewSyscallError("Cmd.Start", err)) os.Exit(1) } b, _ := io.ReadAll(o) fmt.Printf("%s\n", b) if err := c.Wait(); err != nil { fmt.Printf("中断時刻:[%s]\n", time.Now().Format(layout)) fmt.Fprintf(os.Stderr, "%v\n", os.NewSyscallError("Cmd.Wait", err)) os.Exit(1) } fmt.Printf("終了時刻:[%s]\n", time.Now().Format(layout)) }
◆実行結果(Windows)
◆実行結果(Windows)
最後までご覧いただきありがとうございます