使用該os/exec軟體包,我想在 *nix 作業系統上使用另一個用戶而不是 root 運行外部命令。(主行程在root用戶下運行)。
外部命令由 go app 運行。但我的應用程式無法讀取/proc/pid/smaps檔案,出現以下錯誤:
panic: open /proc/2962/smaps: permission denied
goroutine 6 [running]:
main.memwatch(0xc000094000, 0xc00007a0c0)
/src/main.go:41 0x298
created by main.main
/src/main.go:25 0x18f
exit status 2
這是我的代碼:
// main.go
package main
import (
"fmt"
"os"
"os/exec"
"syscall"
"time"
)
func main() {
cmd := exec.Command("sleep", "3")
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
Credential: &syscall.Credential{Uid: 65534, Gid: 65534}, // External command expect run with `nobody` instead of `root` for security reason
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Start()
done := make(chan struct{})
go memwatch(cmd, done)
if err != nil {
panic(err)
}
cmd.Wait()
close(done)
}
func memwatch(cmd *exec.Cmd, done <-chan struct{}) {
// Reuse the reader so we don't have to close and reopen it all the time
smaps, err := os.Open(fmt.Sprintf("/proc/%d/smaps", cmd.Process.Pid))
if err != nil {
panic(err)
}
defer smaps.Close()
for {
select {
case <-done:
return
default:
fmt.Println("running")
time.Sleep(10 * time.Millisecond)
}
}
}
我累了。任何人在這里尋求幫助,請。
uj5u.com熱心網友回復:
我在沒有SYS_PTRACE功能的 docker 容器中測驗我的代碼。這就是錯誤顯示的原因。當我SYS_PTRACE為該容器添加功能時,錯誤消失了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/438857.html
