如何从 bash 脚本知道用户是否突然关闭 ssh 会话
我有一个 bash 脚本,它充当通过 ssh 登录的用户的默认 shell。 它提供了一个包含多个选项的菜单,其中之一是使用 netcat 发送文件。
我使用的嵌入式 Linux 的 netcat 缺少 -w 选项,因此如果用户在没有发送文件的情况下关闭 ssh 连接,netcat 命令将永远等待。
我需要知道用户是否突然关闭连接,以便脚本可以终止 netcat 命令并正常退出。
到目前为止我尝试过的事情:
- 捕获 SIGHUP:它没有发出。我能找到的唯一发出的信号是 SIGCONT,但我认为它不可靠且不便携。
- 使用读取命令的 -t 选项来检测关闭的标准输入:如果不是嵌入式读取命令中的愚蠢错误(仅在第一次调用时超时),这将起作用
编辑:
我'我们将尝试回答评论中的问题并进一步解释情况。
我的代码是:
nc -l -p 7576 > /dev/null 2>> $LOGFILE < $TMP_DIR/$BACKUP_FILE &
wait
我忽略了 SIGINT 和 SIGTSTP,但我尝试捕获所有信号,但收到的唯一信号是 SIGCONT。
阅读 bash 手册页,我发现 SIGHUP 应该发送到脚本和 netcat,并且 SIGCONT 发送到停止的作业以确保它们收到 SIGHUP。
我猜等待使脚本算作已停止,因此它收到了 SIGCONT,但同时等待以某种方式消耗了 SIGHUP。
所以我尝试更改睡眠等待时间,然后同时收到 SIGHUP 和 SIGCONT 。
问题是:为什么等待会阻塞 SIGHUP?
I have a bash script that acts as the default shell for a user loghing in through ssh.
It provides a menu with several options one of which is sending a file using netcat.
The netcat of the embedded Linux I'm using lacks the -w option, so if the user closes the ssh connection without ever sending the file, the netcat command waits forever.
I need to know if the user abruptly closes the connection so the script can kill the netcat command and exit gracefully.
Things I've tried so far:
- Trapping the SIGHUP: it is not issued. The only signal issued i could find is SIGCONT, but I don't think it's reliable and portable.
- Playing with the -t option of the read command to detect a closed stdin: this would work if not for a silly bug in the embedded read command (only times out on the first invocation)
Edit:
I'll try to answer the questions in the comments and explain the situation further.
The code I have is:
nc -l -p 7576 > /dev/null 2>> $LOGFILE < $TMP_DIR/$BACKUP_FILE &
wait
I'm ignoring SIGINT and SIGTSTP, but I've tried to trap all the signals and the only one received is SIGCONT.
Reading the bash man page I've found out that the SIGHUP should be sent to both script and netcat and that the SIGCONT is sent to stopped jobs to ensure they receive the SIGHUP.
I guess the wait makes the script count as stopped and so it receives the SIGCONT but at the same time the wait somehow eats up the SIGHUP.
So I've tried changing the wait for a sleep and then both SIGHUP and SIGCONT are received.
The question is: why is the wait blocking the SIGHUP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
父级 PID 会改变吗?如果是这样,您可以在进程列表中查找父进程并确保进程名称正确。
Does the Parent PiD change? If so you could look up the parent in the process list and make sure the process name is correct.