简体   繁体   English

为什么我的用于启动和停止服务的 d-bus systemd 命令在具有多个用户的嵌入式系统上因权限错误而失败

[英]Why does my d-bus systemd command to start and stop services fails with permission error on embedded system with multiple users

I am using an embedded system that has multiple users like 'root' and 'user1'.我正在使用具有多个用户的嵌入式系统,例如“root”和“user1”。 I am running a c++ binary logged in as 'user1' and It fails to start / stop a service with a permission error.我正在运行以“user1”身份登录的 c++ 二进制文件,但由于权限错误而无法启动/停止服务。 The same binary when running in root works fine.在 root 中运行时相同的二进制文件可以正常工作。 Here is the code:这是代码:

#include <iostream>
#include <systemd/sd-bus.h>


static void SDCallMethodSS(
  sd_bus* bus,
  const std::string& name,
  const std::string& method)
{
  sd_bus_error err = SD_BUS_ERROR_NULL;
  sd_bus_message* msg = nullptr;
  int r;

  r = sd_bus_call_method(bus,
      "org.freedesktop.systemd1",
      "/org/freedesktop/systemd1",
      "org.freedesktop.systemd1.Manager",
      method.c_str(),
      &err,
      &msg,
      "ss",
      name.c_str(),  "replace" );

  if (r < 0)
  {
    std::string err_str("Could not send " + method +
                        " command to systemd for service: " + name +
                        ". Error: " + err.message );

    sd_bus_error_free(&err);
    sd_bus_message_unref(msg);
    throw std::runtime_error(err_str);
  }

  char* response;
  r = sd_bus_message_read(msg, "o", &response);
  if (r < 0)
  {
          std::cerr<< "Failed to parse response message: " << strerror(-r) << std::endl;;
  }

  sd_bus_error_free(&err);
  sd_bus_message_unref(msg);
}

int main() {
  int r;
  sd_bus *bus = NULL;

  r = sd_bus_open_system(&bus);
  if (r < 0) {
          std::cerr<< "Failed to connect to system bus: " << strerror(-r) << std::endl;
    return -1;
  }

  try{
    SDCallMethodSS(bus, std::string("foo-daemon.service"), std::string("StopUnit"));
  } catch (std::exception& e) {
    std::cout << "Exception in SDCallMethodSS(): " << e.what() << std::endl;
    return -2;
  }
}

Foo-daemon is a dummy program: Foo-daemon 是一个虚拟程序:

#include <unistd.h>

int main()
{
  while(1){
    sleep(1);
  }

}

The service file is simple:服务文件很简单:

[Unit]
Description=Foo

[Service]
ExecStart=/usr/local/bin/foo-daemon

[Install]
WantedBy=multi-user.target

Service file is loaded into /etc/systemd/system Output for 'user1' is:服务文件被加载到 /etc/systemd/system Output 中,'user1' 是:

Exception in SDCallMethodSS(): Could not send StopUnit command to systemd for service: foo-daemon.service. Error: Permission denied

How do I address the permissions issue for 'user1'如何解决“user1”的权限问题

Change the permission of file /usr/local/bin/foo-daemon.更改文件 /usr/local/bin/foo-daemon 的权限。

chmod 755 /usr/local/bin/foo-daemon

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM