]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
core: set $SYSTEMD_EXEC_PID= environment variable for executed commands
authorYu Watanabe <watanabe.yu+github@gmail.com>
Tue, 26 Jan 2021 06:56:42 +0000 (15:56 +0900)
committerYu Watanabe <watanabe.yu+github@gmail.com>
Sun, 31 Jan 2021 16:13:44 +0000 (01:13 +0900)
It may be useful to detect a command is directly executed by systemd
manager, or indirectly as a child of another process.

man/systemd.exec.xml
src/core/execute.c

index 203fc0355d746c8b6875b7a801d9245c0563fee9..5b5590a2336d785546769469212ffa7179c24d84 100644 (file)
@@ -3043,6 +3043,17 @@ StandardInputData=SWNrIHNpdHplIGRhIHVuJyBlc3NlIEtsb3BzLAp1ZmYgZWVtYWwga2xvcHAncy
           </para></listitem>
         </varlistentry>
 
+        <varlistentry>
+          <term><varname>$SYSTEMD_EXEC_PID</varname></term>
+
+          <listitem><para>The PID of the unit process (e.g. process invoked by
+          <varname>ExecStart=</varname>). The child process can use this information to determine
+          whether the process is directly invoked by the service manager or indirectly as a child of
+          another process by comparing this value with the current PID (as similar to the scheme used in
+          <citerefentry><refentrytitle>sd_listen_fds</refentrytitle><manvolnum>3</manvolnum></citerefentry>
+          with <varname>$LISTEN_PID</varname> and <varname>$LISTEN_FDS</varname>).</para></listitem>
+        </varlistentry>
+
         <varlistentry>
           <term><varname>$TERM</varname></term>
 
index b7d78f2197e143e1b781b29b26bafefedc978c6d..29fe9f05b12ae59ac8aec200f43d28799ba6d4ea 100644 (file)
@@ -1794,7 +1794,7 @@ static int build_environment(
         assert(p);
         assert(ret);
 
-#define N_ENV_VARS 16
+#define N_ENV_VARS 17
         our_env = new0(char*, N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX);
         if (!our_env)
                 return -ENOMEM;
@@ -1950,6 +1950,11 @@ static int build_environment(
                 our_env[n_env++] = x;
         }
 
+        if (asprintf(&x, "SYSTEMD_EXEC_PID=" PID_FMT, getpid_cached()) < 0)
+                return -ENOMEM;
+
+        our_env[n_env++] = x;
+
         our_env[n_env++] = NULL;
         assert(n_env <= N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX);
 #undef N_ENV_VARS