Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I terminate backgrounded ssh instances
    primarykey
    data
    text
    <p>I have written C program that uses fork(2) and execl(3) to run ssh for port forwarding purposes. The ssh's are run in the background the -f option.</p> <p>When the C program exits, I want it to send SIGTERM to the ssh instances it spawned.</p> <p>I have tried</p> <pre><code>// creating the ssh process ssh_pid = fork(); if (ssh_pid == 0) execl("/usr/bin/ssh", "/usr/bin/ssh", "-f", other options, NULL) // ... printf("Killing %d\n", ssh_pid); // &lt;--- output the PID kill(ssh_pid, 15); sleep(1); // give it a chance to exit properly if (kill(ssh_pid, 0) == 0) kill(ssh_pid, 9); // the "shotgun" approach </code></pre> <p>However, this doesn't work (even with the SIGKILL).</p> <p>If I run ps <em>before the program exits</em></p> <pre><code>ps aux | grep ssh | grep -v sshd | grep -v grep </code></pre> <p>I see something like this:</p> <pre><code>user 27825 0.2 0.0 0 0 pts/0 Z+ 18:23 0:00 [ssh] &lt;defunct&gt; user 27834 0.0 0.0 41452 1176 ? Ss 18:23 0:00 /usr/bin/ssh -f [other options] </code></pre> <p>When the program prints the PID it is killing, I see this:</p> <pre><code>Killing 27825 </code></pre> <p>Subsequently repeating the ps gives me:</p> <pre><code>user 27834 0.0 0.0 41452 1176 ? Ss 18:23 0:00 /usr/bin/ssh -f [other options] </code></pre> <p>It seems that the original ssh has forked itself in order to become a background process.</p> <p>So I changed my call to kill(2) to attempt to kill all processes spawned by the original ssh:</p> <pre><code>kill(-ssh_pid, 15); </code></pre> <p>But this appears to have no effect. I suspect it is because the original ssh is no longer the parent of the backgrounded ssh.</p> <p>So, how do I safely kill the backgrounded ssh? Is it even possible?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload