在子线程中终止使用 system() 启动的程序

Kill the program launched with system() in child thread

我有一个主程序,我使用 pthread_create() 从中创建了两个线程。在一个线程中,我调用

线程我 { ... 系统(“二进制应用程序”);

}

System() 在内部派生了一个子进程。我怎样才能从主程序中杀死那个“二进制应用程序”?

没有直接支持。

您需要 PID 来终止进程,而 system() 是为同步执行某些命令而设计的——它不会公开所调用命令的 PID。事实上,system() 可能会产生几个 PID,几代后代,可能 /bin/sh 然后是你的 binary-application

如何从外部进程(不是线程,完全是外部进程)杀死binary-application?然而,你这样做可能是你的终止线程如何获得 PID。

set an alarm on the command, or instead call fork() (which gives you the PID) and exec() in your own code. In any case, system() in a multithreaded program can be tricky可能更容易,所以要小心。