3-4天前,我开始学习bash,我有一项任务要做,我很难完成这项任务。我需要创建一个脚本,运行一个循环,在发出信号后,它应该打印进程id并退出。如果我能得到帮助,我会非常感激的。
发布于 2021-08-09 12:39:31
你会这样做的:
#!/usr/bin/env bash
# Our USR1 signal handler
usr1_trap(){
printf 'Here is the PID: %d\nExiting right-now!\n' $$
exit
}
# Register USR1 signal handler
trap usr1_trap USR1
printf 'Run this to stop me:\nkill -USR1 %d\n' $$
# Wait in background, not consuming CPU
while :; do
sleep 9223372036854775807 & # int max (2^63 - 1)
wait $!
done发布于 2021-08-09 11:43:10
当接收到信号时,可以添加trap命令来执行命令:
trap 'echo "Hmm, SIGUSR1??!"' SIGUSR1为了使代码更清晰,让我们使用一个函数来完成这个任务:
exit_program(){
echo "Here is the PID: $$"
exit
}如何调用陷阱中的函数?
trap "exit_program" SIGUSR1希望这将是有益的:
#!/usr/bin/env bash
# Cancel Program
exit_program(){
echo "Here is the PID: $$"
exit
}
# Reciever
trap "exit_program" SIGUSR1https://stackoverflow.com/questions/68710657
复制相似问题