我制定了这个polkit规则:
polkit.addRule(function(action, subject) {
if (action.id == "org.freedesktop.systemd1.manage-units") {
return "yes";
}
});
它适用于以下命令,我不需要是root来启动/停止。
busctl call org.freedesktop.systemd1 /org/freedesktop/systemd1 org.freedesktop.systemd1.Manager StopUnit ss "cups.service" "replace"
但是,我已经编写了一个C程序来启动/停止服务并且它不起作用,无论我做什么,我都会收到此错误(除非我以root身份运行):
Name Error (Connection ":1.689" is not allowed to own the service "org.freedesktop.systemd1" due to security policies in the configuration file)
这是该程序的源代码,为清楚起见,我删除了错误检查。
#include <stdlib.h>
#include <stdio.h>
#include <dbus/dbus.h>
int main(int argc, char *argv[])
{
const char* params = "cups.service fail";
const char* destination = "org.freedesktop.systemd1";
const char* path = "/org/freedesktop/systemd1";
const char* interface = "org.freedesktop.systemd1.Manager";
const char* method = "StopUnit";
DBusMessage* msg;
DBusMessage *response;
DBusMessageIter args;
DBusPendingCall* pending;
DBusError err;
DBusConnection* conn;
int ret;
// connect to the bus
conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
// The error happens here
ret = dbus_bus_request_name(conn,
destination,
DBUS_NAME_FLAG_REPLACE_EXISTING,
&err);
msg = dbus_message_new_method_call(destination, // target for the method call
path, // object to call on
interface, // interface to call on
method); // method name
dbus_message_iter_init_append(msg, &args);
dbus_connection_send_with_reply(conn, msg, &pending, -1);
dbus_connection_flush(conn);
dbus_message_unref(msg);
This应用似乎做了类似的事情。