douguanyun2169 2019-06-06 07:33
浏览 151

如何编写可以切换到bash的shell?

I want to switch to the bash shell from my custom shell in go.

I am not sure how to sleep my parent process (custom shell) and switch to the child process (bash)

This is my part of the code.

    cmd := exec.Command("bash", "-c", "/bin/bash")
    stdoutStderr, err := cmd.CombinedOutput()
    if err != nil {
        fmt.Printf(err.Error())
    }
    fmt.Printf("%s
", stdoutStderr)

I want to do it as follows:

myshell >> /bin/bash
$ /bin/myshell
myshell >>

the code is exec but not fork

    binary, lookErr := exec.LookPath("/bin/bash")
    if lookErr != nil {
        panic(lookErr)
    }

    args := []string{"/bin/bash"}

    env := os.Environ()

    execErr := syscall.Exec(binary, args, env)
    if execErr != nil {
        panic(execErr)
    }

so if I exit the bash shell, of course, my custom shell is killed.

myshell> bash
bash-3.2$ exit
exit
  • 写回答

2条回答 默认 最新

  • drpjdfj618393 2019-06-06 07:40
    关注

    This is a recipe for how to stop a process and let the parent shell process take over control. I'm not sure if you can use it to do the opposite.

    The idea is to send a stop signal to yourself.

    pid := os.Getpid()
    process, err := os.FindProcess(pid)
    if err != nil {
        err = errors.Wrapf(err, "error pausing process %+v", process)
        return
    }
    process.Signal(syscall.SIGSTOP)
    

    Source https://github.com/grzegorz-zur/bare-minimum/blob/95fb116631b6146707c47455d8ffce6bb5b8717c/editor.go#L152

    Earlier you need to listen in a goroutine to continue signal to reinitialize your process if needed

    signals := make(chan os.Signal, 1)
    signal.Notify(signals, syscall.SIGCONT, syscall.SIGTERM)
    for signal := range signals {
        switch signal {
        case syscall.SIGCONT:
            // reinitialize
        case syscall.SIGTERM:
            // stop
        }
    }
    

    Source https://github.com/grzegorz-zur/bare-minimum/blob/95fb116631b6146707c47455d8ffce6bb5b8717c/editor.go#L87

    评论

报告相同问题?

悬赏问题

  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?