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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘