Skip to content

Commit f5a75de

Browse files
author
Luca Bruno
authored
Merge pull request #385 from dylanratcliffe/get-unit-pid
dbus: add support for querying unit by PID
2 parents f9f2546 + fd56b73 commit f5a75de

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

dbus/methods.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,29 @@ func (c *Conn) listUnitsInternal(f storeFunc) ([]UnitStatus, error) {
417417
return status, nil
418418
}
419419

420+
// GetUnitByPID returns the unit object path of the unit a process ID
421+
// belongs to. It takes a UNIX PID and returns the object path. The PID must
422+
// refer to an existing system process
423+
func (c *Conn) GetUnitByPID(ctx context.Context, pid uint32) (dbus.ObjectPath, error) {
424+
var result dbus.ObjectPath
425+
426+
err := c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.GetUnitByPID", 0, pid).Store(&result)
427+
428+
return result, err
429+
}
430+
431+
// GetUnitNameByPID returns the name of the unit a process ID belongs to. It
432+
// takes a UNIX PID and returns the object path. The PID must refer to an
433+
// existing system process
434+
func (c *Conn) GetUnitNameByPID(ctx context.Context, pid uint32) (string, error) {
435+
path, err := c.GetUnitByPID(ctx, pid)
436+
if err != nil {
437+
return "", err
438+
}
439+
440+
return unitName(path), nil
441+
}
442+
420443
// Deprecated: use ListUnitsContext instead.
421444
func (c *Conn) ListUnits() ([]UnitStatus, error) {
422445
return c.ListUnitsContext(context.Background())

dbus/methods_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,38 @@ func TestReloadOrRestartUnit(t *testing.T) {
450450
}
451451
}
452452

453+
// Ensure that GetUnitByPID works.
454+
func TestGetUnitByPID(t *testing.T) {
455+
conn := setupConn(t)
456+
defer conn.Close()
457+
458+
path, err := conn.GetUnitByPID(context.Background(), 1)
459+
460+
if err != nil {
461+
t.Error(err)
462+
}
463+
464+
if path == "" {
465+
t.Fatal("path is empty")
466+
}
467+
}
468+
469+
// Ensure that GetUnitNameByPID works.
470+
func TestGetUnitNameByPID(t *testing.T) {
471+
conn := setupConn(t)
472+
defer conn.Close()
473+
474+
name, err := conn.GetUnitNameByPID(context.Background(), 1)
475+
476+
if err != nil {
477+
t.Error(err)
478+
}
479+
480+
if name == "" {
481+
t.Fatal("name is empty")
482+
}
483+
}
484+
453485
// Ensure that ListUnitsByNames works.
454486
func TestListUnitsByNames(t *testing.T) {
455487
target1 := "systemd-journald.service"

0 commit comments

Comments
 (0)