You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pkexec以高权限启动Avalonia应用时出现XOpenDisplay失败问题

问题:pkexec启动Avalonia图形应用报错XOpenDisplay failed

尝试用pkexec以高权限运行Avalonia框架开发的图形应用,执行命令:

pkexec /home/depaula/MyApp/RedundancyServerIHM

出现以下错误:

Unhandled exception. System.Exception: XOpenDisplay failed
   at Avalonia.X11.AvaloniaX11Platform.Initialize(X11PlatformOptions options)
   at Avalonia.AvaloniaX11PlatformExtensions.<>c.<UseX11>b__0_0()
   at Avalonia.AppBuilder.SetupUnsafe()
   at Avalonia.AppBuilder.Setup()
   at Avalonia.AppBuilder.SetupWithLifetime(IApplicationLifetime lifetime)
   at Avalonia.ClassicDesktopStyleApplicationLifetimeExtensions.StartWithClassicDesktopLifetime(AppBuilder builder, String[] args)
   at RedundancyIHM.Avalonia.Program.Main(String[] args) in C:\Users\otavio.paula\Documents\\RedundancyServerIHM.Avalonia\Program.cs:line 12
   Aborted (core dumped)

该应用以普通用户身份运行正常,但pkexec启动时无法连接X11服务器。已执行xhost +SI:localuser:root为root授权X11访问权限,但问题依旧。


解决方法

方法1:手动传递X11环境变量给pkexec

pkexec默认不会继承当前用户的X11相关环境变量,需显式传递:

pkexec env DISPLAY=$DISPLAY XAUTHORITY=$XAUTHORITY /home/depaula/MyApp/RedundancyServerIHM
  • DISPLAY:指定X11服务器的显示编号,通常为:0
  • XAUTHORITY:指向当前用户的X认证文件,默认路径为~/.Xauthority

方法2:修改pkexec策略文件,自动继承X11环境

创建规则文件/etc/polkit-1/rules.d/50-redundancy-server-ihm.rules,内容如下:

polkit.addRule(function(action, subject) {
    if (action.id == "org.freedesktop.policykit.exec" &&
        action.lookup("program") == "/home/depaula/MyApp/RedundancyServerIHM") {
        return polkit.Result.YES;
    }
});

再创建对应的policy文件/usr/share/polkit-1/actions/com.example.RedundancyServerIHM.policy:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC
 "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
 "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
<policyconfig>
  <action id="org.freedesktop.policykit.exec">
    <defaults>
      <allow_any>auth_admin</allow_any>
      <allow_inactive>auth_admin</allow_inactive>
      <allow_active>auth_admin</allow_active>
    </defaults>
    <annotate key="org.freedesktop.policykit.exec.path">/home/depaula/MyApp/RedundancyServerIHM</annotate>
    <annotate key="org.freedesktop.policykit.exec.allow_gui">true</annotate>
  </action>
</policyconfig>

添加allow_gui注解后,pkexec会自动加载必要的X11环境变量,之后直接执行原pkexec命令即可。

方法3:用sudo替代pkexec(若系统允许)

sudo默认保留更多环境变量,执行:

sudo -E /home/depaula/MyApp/RedundancyServerIHM
  • -E参数用于保留当前用户的环境变量,包括X11相关的DISPLAY和XAUTHORITY

方法4:验证并修复root用户的X11认证权限

执行以下命令确认root用户是否有当前X11会话的认证条目:

sudo xauth list

若缺少对应$DISPLAY的条目,从普通用户复制认证信息:

sudo xauth add $(xauth list $DISPLAY)

完成后再尝试用pkexec启动应用。


内容的提问来源于stack exchange,提问作者Worst Noob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 02:37:18