gpt4 book ai didi

bash - 如何在shell脚本中处理Ctrl + c?

转载 作者:行者123 更新时间:2023-12-04 16:18:19 24 4
gpt4 key购买 nike

我正在尝试处理 shell 脚本中的 ctrl + c。我有代码在 while 循环中运行,但我从脚本调用二进制文件并在后台运行它,所以当我想停止二进制文件时应该停止。代码在 hello.c 下面
vim 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);


}
}
下面是我使用的 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
启动脚本后,hello 二进制文件将持续运行。我已经使用 kill -9 pid 命令从其他终端杀死了这个二进制文件。
我试过这个 trap_ctrlc 函数,但它不起作用。如何处理 shell 脚本中的 Ctrl + c。
在 in.txt 中,我添加了输入,因此我可以将此文件直接传递给二进制文件
vim.txt
1
2
输出:
输入第一个数字
输入第二个数字
输入的数字是 n1 = 1 , n2 =2
输入第一个数字
输入第二个数字
输入的数字是 n1 = 1 , n2 =2
输入第一个数字
输入第二个数字
输入的数字是 n1 = 1 , n2 =2
并且它不断地进行。

最佳答案

更改您的 程序,因此它检查读取数据是否确实成功:

#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);
}
}
它现在将在来自 in.txt 的输入时终止耗尽。
制作来自 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
可能的输出:
$ ./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
另一种选择是在 wait 之后杀死 child 。被打断:
#!/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)"`
``

关于bash - 如何在shell脚本中处理Ctrl + c?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64159363/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com