當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


GO CommandContext用法及代碼示例

GO語言"os/exec"包中"CommandContext"函數的用法及代碼示例。

用法:

func CommandContext(ctx context.Context, name string, arg ...string) *Cmd

CommandContext 與 Command 類似,但包含上下文。

如果上下文在命令自行完成之前完成,則提供的上下文用於終止進程(通過調用 os.Process.Kill)。

例子:

package main

import (
    "context"
    "os/exec"
    "time"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
    defer cancel()

    if err := exec.CommandContext(ctx, "sleep", "5").Run(); err != nil {
        // This will fail after 100 milliseconds. The 5 second sleep
        // will be interrupted.
    }
}

相關用法


注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 CommandContext。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。