How to launch a shell command on an already opened specific terminal? - linux

I have a script ./runStart.sh that creates a new xterm and in this xterm launch the script run.log command.
Then, to finish the process I launch a script ./runStop.sh that kills the xterm and do other stuff behind.
The problem I have is that as I kill the process while running, there is no exit call, so the script command does not save the data in the actual file.
Do you know how I could launch a command in the second script ./runStop.sh that makes this exit call instead of the kill <pid> command ?

You can use the bash builtin trap to catch a signal (except KILL and STOP) and do the required cleanup.
For example, here i am catching the pseudo signal EXIT that would cover any signal that would make the shell to exit:
xterm -e '/bin/bash' -c 'trap "echo ok >/tmp/foobar" EXIT; sleep 5'
sleep 5 is my main task and echo ok >/tmp/foobar is cleanup task upon exiting.
Alternately if are sure about the signal to be sent/received e.g. HUP, INT, you can trap those directly.

Related

How to terminate 2 background processes running in bash script?

I want these 2 background processes to end, for example, after pressing CTRL + C, the only thing I found that could help, but this does not work correctly:
python3 script1.py &
python3 script2.py &
trap "trap - SIGTERM && kill -- -$$" SIGINT SIGTERM EXIT
Or is there another solution to run 2 scripts in parallel? Not necessarily in the background.
I would use something in the line of
function killSubproc(){
kill $(jobs -p -r)
}
./test.py one 10 &
./test.py two 5 &
trap killSubproc INT
wait
It is not limited to 2 subprocess, as you can see.
The idea is simply to kill all (still running) process when you hit Ctrl+C
jobs -p -r gives the process number of all running subprocess (-r limits to running subprocess, since some of your script may have terminated naturally ; -p gives process number, not jobs numbers)
And wait, without any argument, wait for all subprocess to end.
That way, your main script is running in foreground while some subtasks are running. It still receives the ctrl+c.
Yet, it terminates if all your subprocess terminates naturally.
And also if you hit ctrl+c
Note: test.py is just a test script I've used, that runs for $2 seconds (10 and 5 here) and display $1 string each second (one and two here)
kill -- -$$ uses $$, the the process id of the shell script, as a group ID. These aren't the same thing.
You need to get the group ID of your shell script and use that. This should work.
ps -o pgid= -p $$
Here's a complete example:
#/bin/bash -e
trap "kill -s INT -- -$(ps -o pgid= -p $$); wait" EXIT
python3 -c 'import time, signal, sys
def handler(a,b):
print("sigint!")
sys.exit(0)
signal.signal(signal.SIGINT, handler)
for i in range(3):
time.sleep(1)
print("hi from python")
' &
sleep 1
With the trap in place, you should see sigint!. With trap commented out, your python will continue to run as you've experienced yourself.
In my example I also added a wait to the trap code to make sure that when the shell script ends, all of the process group also ends.

How to catch SIGINT within a Bash subshell

If I run a command, such as grep, at the command line and hit ^C, the command is properly killed (with SIGINT I think). And if I run the grep in background and then run a kill SIGINT on its PID, it similarly gets terminated. But if I'm inside a script and run grep in background from the script, get its PID and then use 'kill -s SIGINT $PID', grep does not get killed. Why? If I use SIGTERM, instead of SIGINT, the kill does work.
#!/bin/bash
grep -rqa shazam /usr &
PID=$!
kill -s SIGINT $PID
Even if I put the grep in a subprocess, preceded by a SIGINT handler (in the subprocess), and hit the subprocess with SIGINT, the handler is not invoked.
#!/bin/bash
( trap 'echo "caught signal"' SIGINT; grep -rqa shazam /usr ) &
PID=$!
kill -s SIGINT $PID
The trap handler is invoked if I use SIGTERM, instead of SIGINT, but does not interrupt grep. If I add '/bin/kill -s SIGTERM 0' to the trap handler, there is an indication that the grep process gets terminated, but grep has already completed its work by then. I realize that Bash may have different default behaviors for the different signals, but I don't understand why my call to kill SIGINT is different than a ^C, why the trap call works for SIGTERM, but not for SIGINT, nor why SIGTERM isn't handled by the subprocess immediately.
Well, with further digging, I figured out 2 of my 3 questions. When I backgrounded grep within the script, the shell told it to ignore SIGINT. And Bash says it will wait to handle the signal until the subcommand is complete in some situations (which I don't fully follow at the moment), but the signal is handled immediately if hit the grep process directly with pkill.
"Actually bash will disable SIGINT (and SIGQUIT) on background processes and they can't be enabled" Background process and signals How SIGINT works
"Further background jobs are not supposed to be tied to the shell that started them. If you exit a shell, they will continue running. As such they shouldn't be interrupted by SIGINT, not by default. When job control is enabled, that is fulfilled automatically, since background jobs are running in separate process groups. When job control is disabled (generally in non-interactive shells), bash makes the asynchronous commands ignore SIGINT." Independent Program
Reason why SIGTERM works

Get the process ID in a Shell script when a process is launched in foreground

In a shell program I want to launch a program and get its PID and save in a temp file. But here I will launch the program in the foreground and will not exit the shell until the process is in running state
ex:
#!/bin/bash
myprogram &
echo "$!" > /tmp/pid
And this works fine i am able to get the pid of the launched process . But if i launch the program in fore ground i want to know how to get the pid
ex :
#!/bin/bash
myprogram /// hear some how i wan to know the PID before going to next line
As I commented above since your command is still running in foreground you cannot enter a new command in the same shell and goto the next line.
However while this command is running and you want to get the process id of this program from a different shell tab/window process then use pgrep like this:
pgrep -f "myprogram"
17113 # this # will be different for you :P
EDIT: Base on your comment or is it possible to launch the program in background and get the process ID and then wait the script till that process gets exited ?
Yes that can be done using wait pid command as follows:
myprogram &
mypid=$!
# do some other stuff and then
wait $mypid
You can't do this since your shell script isn't running -- the command you just launched in the foreground is.

How to get right PID of a group of background command and kill it?

Ok, just like in this thread, How to get PID of background process?, I know how to get the PID of background process. However, what I need to do countains more than one operation.
{
sleep 300;
echo "Still running after 5 min, killing process manualy.";
COMMAND COMMAND COMMAND
echo "Shutdown complete"
}&
PID_CHECK_STOP=$!
some stuff...
kill -9 $PID_CHECK_STOP
But it doesn't work. It seems i get either a bad PID or I just can't kill it. I tried to run ps | grep sleep and the pid it gives is always right next to the one i get in PID_CHECK_STOP. Is there a way to make it work? Can i wrap those commands an other way so i can kill them all when i need to?
Thx guys!
kill -9 kills the process before it can do anything else, including signalling its children to exit. Use a gentler signal (kill by itself, which sends a TERM, should be sufficient). You do need to have the process signal its children to exit (if any) explicitly, though, via a trap command.
I'm assuming sleep is a placeholder for the real command. sleep is tricky, however, as it ignores any signals until it returns (i.e., it is non-interruptible). To make your example work, put sleep itself in the background and immediately wait on it. When you kill the "outer" background process, it will interrupt the wait call, which will allow sleep to be killed as well.
{
trap 'kill $(jobs -p)' EXIT
sleep 300 & wait
echo "Still running after 5 min, killing process manualy.";
COMMAND COMMAND COMMAND
echo "Shutdown complete"
}&
PID_CHECK_STOP=$!
some stuff...
kill $PID_CHECK_STOP
UPDATE: COMMAND COMMAND COMMAND includes a command that runs via sudo. To kill that process, kill must also be run via sudo. Keep in mind that doing so will run the external kill program, not the shell built-in (there is little difference between the two; the built-in exists to allow you to kill a process when your process quota has been reached).
You can have another script containing those commands and kill that script. If you are dynamically generating code for the block, just write out a script, execute it and kill when you are done.
The { ... } surrounding the statements starts a new shell, and you get its PID afterwards. sleep and other commands within the block get separate PIDs.
To illustrate, look for your process in ps afux | less - the parent shell process (above the sleep) has the PID you were just given.

How to Kill Current Command When Bash Script is Killed

I current have a script that looks like this.
# code
mplayer "$vid"
# more code
The problem is that if this script is killed the mplayer process lives. I wondering how I could make it so that killing the script would kill mplayer as well.
I can't use exec because I need to run commands after mplayer.
exec mplayer "$vid"
The only possible solution I can think of is to spawn it in the background and wait until it finishes manually. That way I can get it's PID and kill it when the script gets killed, not exactly elegant. I was wondering what the "proper" or best way of doing this is.
I was able to test the prctl idea I posted about in a comment and it seems to work. You will need to compile this:
#include "sys/prctl.h"
#include "stdlib.h"
#include "string.h"
#include "unistd.h"
int main(int argc, char ** argv){
prctl(PR_SET_PDEATHSIG, atoi(argv[1]),0,0,0);
char * argv0 = strdup(argv[2]);
char * slashptr = strrchr(argv0, '/');
if(slashptr){
argv0 = slashptr + 1;
}
return execvp(argv0, &(argv[2]));
}
Let's say you have compiled the above to an executable named "prun" and it is in your path. Let's say your script is called "foo.sh" and it is also in your path. Make a wrapper script that calls
prun 15 foo.sh
foo.sh should get SIGTERM when the wrapper script is terminated for any reason, even SIGKILL.
Note: this is a linux only solution and the c source code presented is without detailed checking of arguments
Thanks to Mux for the lead. It appears that there is no way to do this in bash except for manually catching signals. Here is a final working (overly commented) version.
trap : SIGTERM SIGINT # Trap these two (killing) signals. These will cause wait
# to return a value greater than 128 immediately after received.
mplayer "$vid" & # Start in background (PID gets put in `$!`)
pid=$!
wait $pid # Wait for mplayer to finish.
[ $? -gt 128 ] && { kill $pid ; exit 128; } ; # If a signal was recieved
# kill mplayer and exit.
Refrences:
- traps: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_12_02.html
(Updated) I think I understand what you are looking for now:
You can accomplish this by spawning a new terminal to run your script:
gnome-terminal -x /path_to_dir_of_your_script/your_script_name
(or use xterm -e or konsole -e instead of gnome-terminal -x, depending on what system you are on)
So now whenever your script ends / exits (I assume you have exit 0 or exit 1 in certain parts of the script), the newly spawned terminal will also exit since the script is finished - this will in turn also kill any applications spawned under that new terminal.
For example, I just tested the above command with this script:
#!/bin/bash
gedit &
pid=$!
echo "$pid"
sleep 5
exit 0
As you can see, there are no explicit calls to kill the new gedit process, but the application (gedit) closes as soon as the script exits anyway.
(Previous answer: alternatively, if you were simply asking about how to kill a process) Here's a short example of how you can accomplish that with kill.
#!/bin/bash
gedit &
pid=$!
echo "$pid"
sleep 5
kill -s SIGKILL $pid
Unless I misunderstood your question, you can get the PID of the spawned process right away instead of waiting until it finishes.
Well, you can simply kill the process group instead, this way the whole process tree will be killed, first find out the group id
ps x -o "%p %r %c" | grep <name>
And then use kill like so:
kill -TERM -<gid>
Note the dash before the process group id. Or a one-liner:
kill -TERM -$(pgrep <name>)
Perhaps use command substitution to run mplayer "$vid" in a subshell:
$(mplayer "$vid")
I tested it this way:
tesh.sh:
#!/bin/sh
$vid = "..."
$(mplayer "$vid")
% test.sh
In a separate terminal:
% pkill test.sh
In the orginal terminal, mplayer stops, printing to stderr
Terminated
MPlayer interrupted by signal 13 in module: av_sync

Resources