From 716d96b8eb00f0f43a01d1707cbc1d611c10454b Mon Sep 17 00:00:00 2001
From: Lukas Nykryn <lnykryn@redhat.com>
Date: Tue, 16 Apr 2013 15:58:32 +0200
Subject: [PATCH] ps: possibility to display login session for a process

Library systemd-login offers possibility to display name
of login session for specific pid.
Note that not all processes are part of a login session
(e.g. system service processes, user processes that are shared
between multiple sessions of the same user, or kernel threads).

This patch adds output option "sd_session" which will
show name of session or "-", when process does not belong
to any session.

To maintain compatibility with non-systemd systems,
procps must be configured with --with-systemd option
to enable this option.
---
 ps/output.c | 20 ++++++++++++++++++++
 ps/ps.1     |  4 ++++
 2 files changed, 24 insertions(+)

diff --git a/ps/output.c b/ps/output.c
index 39b77637..f1cf6bc0 100644
--- a/ps/output.c
+++ b/ps/output.c
@@ -1191,6 +1191,25 @@ fail:
   outbuf[1] = '\0';
   return 1;
 }
+
+static int pr_sd_session(char *restrict const outbuf, const proc_t *restrict const pp){
+  int r;
+  size_t len;
+  char *session;
+
+  r = sd_pid_get_session(pp->tgid, &session);
+  if(r<0) goto fail;
+  len = snprintf(outbuf, COLWID, "%s", session);
+  free(session);
+  return len;
+
+fail:
+  outbuf[0] = '-';
+  outbuf[1] = '\0';
+  return 1;
+}
+
+
 #endif
 /****************** FLASK & seLinux security stuff **********************/
 // move the bulk of this to libproc sometime
@@ -1519,6 +1538,7 @@ static const format_struct format_array[] = {
 {"scnt",      "SCNT",    pr_nop,      sr_nop,     4,   0,    DEC, AN|RIGHT},  /* man page misspelling of scount? */
 {"scount",    "SC",      pr_nop,      sr_nop,     4,   0,    AIX, AN|RIGHT},  /* scnt==scount, DEC claims both */
 #ifdef WITH_SYSTEMD
+{"sd_session","SESSION", pr_sd_session, sr_nop,  11,   0,    LNX, ET|LEFT},
 {"sd_unit",   "UNIT",    pr_sd_unit,  sr_nop,    31,   0,    LNX, ET|LEFT},
 #endif
 {"sess",      "SESS",    pr_sess,     sr_session, 5,   0,    XXX, PO|PIDMAX|RIGHT},
diff --git a/ps/ps.1 b/ps/ps.1
index 0d66cf95..f953e23a 100644
--- a/ps/ps.1
+++ b/ps/ps.1
@@ -1489,6 +1489,10 @@ SCHED_FIFO, SCHED_RR, SCHED_BATCH, SCHED_ISO, and SCHED_IDLE are respectively
 displayed as 0, 1, 2, 3, 4, and 5.
 T}
 
+sd_session	SESSION	T{
+displays login session identifier of a process.
+T}
+
 sd_unit	UNIT	T{
 displays systemd unit which a process belongs to.
 T}
-- 
2.40.0