diff --git a/dbus/methods.go b/dbus/methods.go index f577ab37..074148cb 100644 --- a/dbus/methods.go +++ b/dbus/methods.go @@ -417,6 +417,29 @@ func (c *Conn) listUnitsInternal(f storeFunc) ([]UnitStatus, error) { return status, nil } +// GetUnitByPID returns the unit object path of the unit a process ID +// belongs to. It takes a UNIX PID and returns the object path. The PID must +// refer to an existing system process +func (c *Conn) GetUnitByPID(ctx context.Context, pid uint32) (dbus.ObjectPath, error) { + var result dbus.ObjectPath + + err := c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.GetUnitByPID", 0, pid).Store(&result) + + return result, err +} + +// GetUnitNameByPID returns the name of the unit a process ID belongs to. It +// takes a UNIX PID and returns the object path. The PID must refer to an +// existing system process +func (c *Conn) GetUnitNameByPID(ctx context.Context, pid uint32) (string, error) { + path, err := c.GetUnitByPID(ctx, pid) + if err != nil { + return "", err + } + + return unitName(path), nil +} + // Deprecated: use ListUnitsContext instead. func (c *Conn) ListUnits() ([]UnitStatus, error) { return c.ListUnitsContext(context.Background()) diff --git a/dbus/methods_test.go b/dbus/methods_test.go index 55bc2c9c..30cc1324 100644 --- a/dbus/methods_test.go +++ b/dbus/methods_test.go @@ -450,6 +450,38 @@ func TestReloadOrRestartUnit(t *testing.T) { } } +// Ensure that GetUnitByPID works. +func TestGetUnitByPID(t *testing.T) { + conn := setupConn(t) + defer conn.Close() + + path, err := conn.GetUnitByPID(context.Background(), 1) + + if err != nil { + t.Error(err) + } + + if path == "" { + t.Fatal("path is empty") + } +} + +// Ensure that GetUnitNameByPID works. +func TestGetUnitNameByPID(t *testing.T) { + conn := setupConn(t) + defer conn.Close() + + name, err := conn.GetUnitNameByPID(context.Background(), 1) + + if err != nil { + t.Error(err) + } + + if name == "" { + t.Fatal("name is empty") + } +} + // Ensure that ListUnitsByNames works. func TestListUnitsByNames(t *testing.T) { target1 := "systemd-journald.service"