TERM 的 bash 陷阱 - 我做错了什么?

发布于 2024-08-07 01:47:16 字数 696 浏览 5 评论 0原文

给定这个 hack.c 程序:

#include <stdio.h>
main()
{
 int i=0;
 for(i=0; i<100; i++) {
   printf("%d\n", i);
   sleep(5);
 }
}

和这个 hack.sh bash 脚本:

#!/bin/bash
./hack

如果我运行 hack.sh,则会创建两个进程 - 一个用于 bash,一个用于 C 任务。如果 TERM 信号被发送到 bash 进程,则 C 进程不会受到损害。

现在,假设原始 bash 是使用 Runtime.exec() 从 Java 程序启动的,所以我对它的唯一控制是 Process.destroy() (它将 TERM 发送到 bash 进程)?假设我希望 C 进程与启动它的 bash 一起终止?

我一直在 bash 中尝试这样的事情:

#!/bin/bash
trap "kill -TERM -$$; exit" TERM
./hack

即捕获 TERM 信号并将其重新广播到整个进程组的 trap 子句。这对我不起作用 - 带有 trap 子句的 bash 进程忽略 TERM 信号。

我在这里缺少什么?

Given this hack.c program:

#include <stdio.h>
main()
{
 int i=0;
 for(i=0; i<100; i++) {
   printf("%d\n", i);
   sleep(5);
 }
}

and this hack.sh bash script:

#!/bin/bash
./hack

If I run hack.sh, two processes get created - one for bash, one for the C task. If a TERM signal gets sent to the bash process, the C process is unharmed.

Now, suppose the original bash was launched from a Java program using Runtime.exec(), so the only control I have over it is Process.destroy() (which sends TERM to the bash process)? Suppose I want the C process to die along with the bash that launched it?

I've been trying things like this in bash:

#!/bin/bash
trap "kill -TERM -$; exit" TERM
./hack

i.e. a trap clause that catches the TERM signal and rebroadcasts it to the whole process group. This doesn't work for me - a bash process with that trap clause in it ignores TERM signals.

What am I missing here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

残月升风 2024-08-14 01:47:16

您可以尝试按照以下方式进行操作:

#!/bin/bash
./hack &
pid=$!
trap "kill $pid" TERM
wait $pid

这样做可能更简单(且等效):

#!/bin/bash
./hack &
trap "kill $!" TERM
wait

陷阱上的双引号应该在定义陷阱时使单词扩展发生,因此 $! 的值会发生变化。不应该有影响;但我更喜欢第一个版本。

You might try something along these lines:

#!/bin/bash
./hack &
pid=$!
trap "kill $pid" TERM
wait $pid

It might be simpler (and equivalent) to do this:

#!/bin/bash
./hack &
trap "kill $!" TERM
wait

The double-quotes on the trap should make word expansion happen when the trap is defined, so a changing value of $! shouldn't have an impact; but I like the first version better.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文