exec.Command()的Golang cmd.Output()在systemd服务(ubuntu)中抛出错误

exec.Command()的Golang cmd.Output()在systemd服务(ubuntu)中抛出错误,ubuntu,go,systemd,Ubuntu,Go,Systemd,我有一个go二进制文件,它使用cmd:=exec.Command(“xdpyinfo”)获取显示信息,然后调用cmd.Output()。 程序在终端中按预期运行。但是,当我将其作为systemd服务运行时,cmd.output()没有输出。 我很抱歉,程序作为服务运行,但调用cmd.Output()返回错误 我已尝试使其尽可能容易复制: 我在/home/myusername/Projects/test 二进制文件是使用包含以下代码的单个main.go文件中的go build生成的: packag

我有一个go二进制文件,它使用
cmd:=exec.Command(“xdpyinfo”)
获取显示信息,然后调用
cmd.Output()
。 程序在终端中按预期运行。但是,当我将其作为systemd服务运行时,
cmd.output()
没有输出。 我很抱歉,程序作为服务运行,但调用cmd.Output()返回错误

我已尝试使其尽可能容易复制:

我在
/home/myusername/Projects/test
二进制文件是使用包含以下代码的单个
main.go
文件中的
go build
生成的:

package main

import (
        "fmt"
        "log"
        "log/syslog"
        "os/exec"
)

func main() {
        logwriter, e := syslog.New(syslog.LOG_NOTICE, "testprog")
        if e == nil {
                log.SetOutput(logwriter)
        }

        cmd := exec.Command("xdpyinfo")

        out, err := cmd.Output()
        if err != nil {
                log.Print(fmt.Errorf("ERROR: %v", err))
        }

        log.Print(string(out))
}
日志记录仅用于测试目的,因为真实代码是更大应用程序的一部分

在终端中运行测试二进制文件时,我在日志中看到了
xdpyinfo
的预期输出。 但是,当尝试在服务中运行相同的二进制文件时,它会输出
错误:退出状态1

我运行该服务所采取的步骤:

  • /etc/systemd/system/TestProg.service
    处创建机组服务文件:
  • 启用服务:
  • sudo systemctl启用TestProg.service

  • 启动服务:
  • sudo systemctl启动测试程序服务

    我还尝试将机组服务文件定位在
    /lib/systemd/system/TestProg.service
    上,并在
    Type=simple
    下添加
    User=username

    我已经尝试了几种不同的配置,试图让它工作。我还尝试使用
    sysprocatr
    (使用实际uid和gid)设置用户:


    我现在开始觉得我遗漏了一些更基本的东西。

    您必须在用户会话中运行它(这也启动了您的X11会话):

    您在没有
    golang
    的情况下执行以下操作:

    sudo systemd-run -t  xdpyinfo 
    Running as unit: run-u2876.service
    Press ^] three times within 1s to disconnect TTY.
    /usr/bin/xdpyinfo:  unable to open display "".
    
    请尝试cmd,err:=exec.Command(“xdpyinfo”).Output()。看不到任何明显的问题。
    cmd := exec.Command("xdpyinfo")
    
    cmd.SysProcAttr = &syscall.SysProcAttr{
      Credential: &syscall.Credential{
        Uid:         uint32(uid),
        Gid:         uint32(gid),
        NoSetGroups: true,
      },
    }
    
    out, err := cmd.Output()
    if err != nil {
            log.Print(fmt.Errorf("ERROR: %v", err))
    }
    
    systemd-run --user -t  xdpyinfo |head
    Running as unit: run-u1614.service
    Press ^] three times within 1s to disconnect TTY.
    name of display:    :0
    version number:    11.0
    vendor string:    The X.Org Foundation
    
    sudo systemd-run -t  xdpyinfo 
    Running as unit: run-u2876.service
    Press ^] three times within 1s to disconnect TTY.
    /usr/bin/xdpyinfo:  unable to open display "".