Search code examples
bashsignals

Bash: Cannot send ctrl+c into started program


I'm trying to write a bash script that starts a program, waits for x seconds and than sends the ctrl+c signal to the program to stop it. The program is "trace-cmd" (which is a frontend for ftrace) that records/traces data until ctrl+c is pressed.

I already found a solution to get the PID of trace-cmd, and to send the SIGINT signal using kill to it. Yet, somehow it does not work.

This is my command that is executed (all in one line, just formatted for readability):

sudo trace-cmd record -p function -P $PID & echo $! > ./pid_trace.txt & 
    echo "[+] Stored PID:" $(cat ./pid_trace.txt) & 
    sleep $seconds; printf "Killing trace-cmd\n"; sudo kill -INT $(cat ./pid_trace.txt)

The 'echo' is just for testing, I used the txt file as I could not assign the $! value to a variable. As far as I understood: the "&" is used so that these commands are executed concurrently and the ";" so that they are executed after each other. So: i should start trace-cmd, store the PID than start the time, and only after the timer is done execute the kill.

When the ctrl+c signal is pressed while executing trace-cmd, a specific output can be seen (basically that the trace is getting stored). Yet, with my bash program I cannot see it. I assume that the kill signal is either not "delivered" or that the SIGINT is not the signal that trace-cmd expects (can a program intercept these signals? or the key-strokes rather)

Any help would be appreciated!


Solution

  • The 'sudo' process does not pass INT signal to it's children. The CTRL/C processing passed the INT signal to all processes running in the foreground for the connected terminal.

    Try one of the options:

    1. Consider using regular kill on sudo (NO -INT). This will use TERM signal, which will result in sudo terminating sub processes.

    2. Send the INT signal directly to the trace (pkill -INT trace_cmd)