我正在尝试在 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 SIGTERM
Run Code Online (Sandbox Code Playgroud)
启动脚本后,hello 二进制文件将持续运行。我已经使用kill -9 pid 命令从其他终端杀死了这个二进制文件。
我尝试过 trap_ctrlc 函数,但它不起作用。如何在shell脚本中处理ctrl+c?
我已经in.txt添加了输入,因此我可以将此文件直接传递给二进制文件。
1
2
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
而且它持续不断。
更改您的c程序,以便检查读取数据是否确实成功:
#include <stdio.h>
int main()
{
int n1,n2;
while(1) {
printf("Enter the first number\n");
if(scanf("%d",&n1) != 1) return 0; /* check here */
printf("Enter the second number\n");
if(scanf("%d",&n2) != 1) return 0; /* check here */
printf("Entered number are n1 = %d , n2 =%d\n",n1,n2);
}
}
Run Code Online (Sandbox Code Playgroud)
当输入in.txt耗尽时,它现在将终止。
要制作可多次读取的内容,您可以在bash脚本中创建一个永远循环(或直到被终止)的in.txt循环。./hello
例子:
#!/bin/bash
# a function to repeatedly print the content in "in.txt"
function print_forever() {
while [ 1 ];
do
cat "$1"
sleep 1
done
}
echo run the hello binary
print_forever in.txt | ./hello &
pid=$!
echo "background process $pid started"
trap_ctrlc() {
kill $pid
echo -e "\nkill=$? (0 = success)\n"
wait $pid
echo "wait=$? (the exit status from the background process)"
echo -e "\n\ntrap_ctrlc\n\n"
}
trap trap_ctrlc INT
# wait for all background processes to terminate
wait
Run Code Online (Sandbox Code Playgroud)
可能的输出:
$ ./hello.sh
run the hello binary
background process 262717 started
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
^C
kill=0 (0 = success)
wait=143 (the exit status from the background process)
trap_ctrlc
Run Code Online (Sandbox Code Playgroud)
另一种选择是在wait中断后杀死孩子:
#!/bin/bash
function print_forever() {
while [ 1 ];
do
cat "$1"
sleep 1
done
}
echo run the hello binary
print_forever in.txt | ./hello &
pid=$!
echo "background process $pid started"
trap_ctrlc() {
echo -e "\n\ntrap_ctrlc\n\n"
}
trap trap_ctrlc INT
# wait for all background processes to terminate
wait
echo first wait=$?
kill $pid
echo -e "\nkill=$? (0 = success)\n"
wait $pid
echo "wait=$? (the exit status from the background process)"`
``
Run Code Online (Sandbox Code Playgroud)