我正在尝试在 shell 脚本中处理 ctrl+c 。我的代码在 while 循环中运行,但我从 shell 脚本调用二进制文件并在后台运行它,因此当我想停止二进制文件时,它应该停止。代码如下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);
}
}
Run Code Online (Sandbox Code Playgroud)
下面是我使用的 bash 脚本。
#/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 …Run Code Online (Sandbox Code Playgroud)