Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在golang程序中运行交互式shell脚本_Go - Fatal编程技术网

在golang程序中运行交互式shell脚本

在golang程序中运行交互式shell脚本,go,Go,我想在golang程序中运行一个交互式shell脚本, 例如包装一个“ping8.8.8.8”、“python”、“bc”、“mysql-H-P-u-P”。 golang程序应该在自己调用完交互命令或shell并与用户保持生成的交互后退出 我尝试过“exec.Command(“python”).Run()”,但golang程序刚刚完成,没有留给我任何东西 func(h ConnectHandler)ConnectMySQL(){ 调试(“ConnectMySQL,脚本:”,common.CONF

我想在golang程序中运行一个交互式shell脚本, 例如包装一个“ping8.8.8.8”、“python”、“bc”、“mysql-H-P-u-P”。 golang程序应该在自己调用完交互命令或shell并与用户保持生成的交互后退出

我尝试过“exec.Command(“python”).Run()”,但golang程序刚刚完成,没有留给我任何东西

func(h ConnectHandler)ConnectMySQL(){
调试(“ConnectMySQL,脚本:”,common.CONF.FilePath.MySQLConnectScriptPath)
err:=exec.Command(“bash”,common.CONF.FilePath.MySQLConnectScriptPath).Run()
如果错误!=零{
logrus.Errorf(“ConnectMySQL失败,退出1,%s”,错误)
操作系统退出(1)
}
}

将命令的stdin、stdout和stderr连接到父进程的stdin、stdout和stderr。另外,在
exec.Command
中向
bash
提供
-c
,否则
bash
将尝试像运行shell脚本一样运行程序

例如,启动交互式Python控制台:

func main() {
    fmt.Println("Before Python shell:")
    cmd := exec.Command("bash", "-c", "/usr/bin/python3")
    cmd.Stdin = os.Stdin
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    _ = cmd.Run() // add error checking
    fmt.Println("After Python shell")
}

听起来您想用您试图启动的命令替换当前进程。启动另一个命令后,Go程序消失,调用方与启动的程序进行交互,就好像它是最初启动的一样

为此,您需要低级函数。你通常不应该指望它会回来。请注意,您需要提供一些详细信息,如要运行的实际二进制文件和高级包装器不需要的环境。(谷歌搜索速度非常快。)


就底层Unix系统调用而言,更高级别的接口,如
os.StartProcess
exec.Cmd
allfork(2)在该子进程中,子进程先于execve(2)。当Go进程退出时,该子进程将成为孤立进程,系统初始化进程将成为其新的父进程。shell只看到Go进程已退出,并将生成一个新的shell提示符。

下面使用Connect命令的stdin、stdout和stderr与父进程的stdin、stdout和stderr的答案有什么区别?在我的答案中没有“父进程”;Go程序将自身替换为exec'd程序,并且父级和进程ID与Go程序相同。在Go中,程序保留并成为子流程的父级;它负责检查错误状态和其他任务。这种方法非常有效。我不明白,为什么它没有收到任何投票。
import "os"
import "syscall"
err := syscall.Exec("/bin/ls", []string{"ls", "-l", "/"}, os.Environ())
// We don't expect this to ever return; if it does something is really wrong
os.panic(err)