从Go程序中调用源代码 [英] Call source from inside a Go program
问题描述
问题是: source
os / exec
命令
函数,因为它需要 PATH
中的可执行文件。 我该怎么做?而且,是否可以在go程序中使 source
影响用户shell?
您可以直接在终端设备中写入命令。但是,要做到这一点,首先需要知道哪个设备正在使用该用户。
#!/ bin / bash
echo从foo脚本运行,pid = $$
go run foo.go`tty`
然后,程序必须将命令写入终端设备。
package main
import(
C
fmt
os
系统调用
不安全
)
func main(){
//获取tty路径
如果len(os.Args)< 2 {
fmt.Printf(no tty path \\\
)
os.Exit(1)
}
ttyPath:= os.Args [1]
//打开tty
tty,err:= os.Open(ttyPath)
if err!= nil {
fmt.Printf(error opening tty:%s \\ \\ n,err.Error())
os.Exit(2)
}
defer tty.Close()
//写入命令
cmd:=echo go from go,pid = $$ \\\
cmdstr:= C.CString(cmd)
cmdaddr:= uintptr(unsafe.Pointer(cmdstr))
for i:= range [] byte(cmd){
_,_,err:= syscall.Syscall(syscall.SYS_IOCTL,tty.Fd(),syscall.TIOCSTI,cmdaddr + uintptr(i))
如果uintptr(err)!= 0 {
fmt.Printf(系统调用错误:%s \ n,err.Error())
os.Exit(3)
$ b code
$ b 下面是一个输出示例: p>
$ echo $$
70318
$ ./foo
跑来跑去m foo脚本,pid = 83035
回声Hello from go,pid = $$
$ echo go from go,pid = $$
你好,go = p $ 70318
请注意,我正在使用 ./
而不是<$执行脚本c $ c> source ,所以脚本的PID不同。但后来,go程序执行的命令具有相同的PID。
For fun and to better learn Go, I'm trying to re-implement antigen in Go.
Problem is: source
is a shell built-in function, so I can't call it with os/exec
Command
function, because it expects an executable in PATH
.
How can I do this? And, is it possible to make a source
from inside a go program affect the user shell?
You can write the command directly in the terminal device. But, to do that, first you need to know which device is using the user. A script that executes your program can be a solution.
#!/bin/bash
echo Running from foo script, pid = $$
go run foo.go `tty`
Then, the program has to write the commands to the terminal device.
package main
import (
"C"
"fmt"
"os"
"syscall"
"unsafe"
)
func main() {
// Get tty path
if len(os.Args) < 2 {
fmt.Printf("no tty path\n")
os.Exit(1)
}
ttyPath := os.Args[1]
// Open tty
tty, err := os.Open(ttyPath)
if err != nil {
fmt.Printf("error opening tty: %s\n", err.Error())
os.Exit(2)
}
defer tty.Close()
// Write a command
cmd := "echo Hello from go, pid = $$\n"
cmdstr := C.CString(cmd)
cmdaddr := uintptr(unsafe.Pointer(cmdstr))
for i := range []byte(cmd) {
_, _, err := syscall.Syscall(syscall.SYS_IOCTL, tty.Fd(), syscall.TIOCSTI, cmdaddr+uintptr(i))
if uintptr(err) != 0 {
fmt.Printf("syscall error: %s\n", err.Error())
os.Exit(3)
}
}
}
Here is an example output:
$ echo $$
70318
$ ./foo
Running from foo script, pid = 83035
echo Hello from go, pid = $$
$ echo Hello from go, pid = $$
Hello from go, pid = 70318
Note that I am executing the script with ./
not source
, so the PID of the script differs. But later, the command executed by the go program has the same PID.
这篇关于从Go程序中调用源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!