I am trying to handle ctrl+c in a shell script. I have code running in a while loop but I am calling the binary from a shell script and running it in the background so when I want to stop the binary it should stop. Code is below of hello.c
#include <stdio.h>
int main()
{
while(1)
{
int n1,n2;
printf("Enter the first number\n");
scanf("%d",&n1);
printf("Enter the second number\n");
scanf("%d",&n2);
printf("Entered number are n1 = %d , n2 =%d\n",n1,n2);
}
}
Below is the bash script which I use.
#/i/bin/sh
echo run the hello binary
./hello < in.txt &
trap_ctrlc()
{
ps -eaf | grep hello | grep -v grep | awk '{print $2}' | xargs kill -9
echo trap_ctrlc
exit
}
trap trap_ctrlc SIGHUP SIGINT SIGTERM
After starting the script the hello binary is running continuously. I have killed this binary from other terminal using kill -9 pid command.
I have tried the trap_ctrlc function but it does not work. How to handle ctrl+c in a shell script?
In in.txt
I have added the input so I can pass this file directly to the binary.
1
2
Output:
Enter the first number
Enter the second number
Entered number are n1 = 1 , n2 =2
Enter the first number
Enter the second number
Entered number are n1 = 1 , n2 =2
Enter the first number
Enter the second number
Entered number are n1 = 1 , n2 =2
And it going continuously.
kill -9
is SIGKILL, you can't trap SIGKILL. See: man7.org/linux/man-pages/man7/signal.7.html You could trykill -HUP
and just plainkill
. – Ichthyology