<p>I am trying to execute a Python program as a background process inside a container with <code>kubectl</code> as below (<code>kubectl</code> issued on local machine):</p>
<p><code>kubectl exec -it &lt;container_id&gt; -- bash -c &quot;cd some-dir &amp;&amp; (python xxx.py --arg1 abc &amp;)&quot;</code></p>
<p>When I log in to the container and check <code>ps -ef</code> I do not see this process running. Also, there is no output from <code>kubectl</code> command itself.</p>
<ul>
<li>Is the <code>kubectl</code> command issued correctly?</li>
<li>Is there a better way to achieve the same?</li>
<li>How can I see the output/logs printed off the background process being run?</li>
<li>If I need to stop this background process after some duration, what is the best way to do this?</li>
</ul>

<p>The <a href="https://en.wikipedia.org/wiki/Nohup#Overcoming_hanging" rel="noreferrer">nohup</a> Wikipedia page can help; you need to redirect all three IO streams (stdout, stdin and stderr) - an example with <code>yes</code>:</p>

<pre><code>kubectl exec pod -- bash -c "yes &gt; /dev/null 2&gt; /dev/null &amp;" 
</code></pre>

<p><code>nohup</code> is not required in the above case because I did not allocate a pseudo terminal (no <code>-t</code> flag) and the shell was not interactive (no <code>-i</code> flag) so no <code>HUP</code> signal is sent to the <code>yes</code> process on session termination. See <a href="https://unix.stackexchange.com/questions/84737/in-which-cases-is-sighup-not-sent-to-a-job-when-you-log-out#answer-85296">this</a> answer for more details.</p>

<p>Redirecting <code>/dev/null</code> to stdin is not required in the above case since stdin already refers to <code>/dev/null</code> (you can see this by running <code>ls -l /proc/YES_PID/fd</code> in another shell).</p>

<p>To see the output you can instead redirect stdout to a file.</p>

<p>To stop the process you'd need to identity the PID of the process you want to stop (<a href="https://linux.die.net/man/1/pgrep" rel="noreferrer">pgrep</a> could be useful for this purpose) and send a fatal signal to it (<code>kill PID</code> for example).</p>

<p>If you want to stop the process after a fixed duration, <a href="https://linux.die.net/man/1/timeout" rel="noreferrer">timeout</a> might be a better option.</p>
