- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我正在使用 Runtime.getRuntime().exec()
命令来启动一个批处理文件,该批处理文件又会为 Windows 平台启动另一个进程。
javaw.exe(Process1)
|___xyz.bat(Process2)
|___javaw.exe(Process3)
Runtime.getRuntime().exec()
返回一个 Process
对象,它有一个 destroy 方法,但是当我使用 destroy()
,它只会杀死 xyz.bat 并使批处理文件的子进程悬空。
是否有一种干净的方法来销毁以批处理为根的进程树?
郑重声明,我不能使用任何自定义库来删除批处理文件来绕过这个问题。
最佳答案
使用标准 Java API 是不可能的(请参阅帖子末尾的编辑以获取更改此内容的更新)。您将需要一些 native 代码。使用 JNA,我使用了如下代码:
public class Win32Process
{
WinNT.HANDLE handle;
int pid;
Win32Process (int pid) throws IOException
{
handle = Kernel32.INSTANCE.OpenProcess (
0x0400| /* PROCESS_QUERY_INFORMATION */
0x0800| /* PROCESS_SUSPEND_RESUME */
0x0001| /* PROCESS_TERMINATE */
0x00100000 /* SYNCHRONIZE */,
false,
pid);
if (handle == null)
throw new IOException ("OpenProcess failed: " +
Kernel32Util.formatMessageFromLastErrorCode (Kernel32.INSTANCE.GetLastError ()));
this.pid = pid;
}
@Override
protected void finalize () throws Throwable
{
Kernel32.INSTANCE.CloseHandle (handle);
}
public void terminate ()
{
Kernel32.INSTANCE.TerminateProcess (handle, 0);
}
public List<Win32Process> getChildren () throws IOException
{
ArrayList<Win32Process> result = new ArrayList<Win32Process> ();
WinNT.HANDLE hSnap = KernelExtra.INSTANCE.CreateToolhelp32Snapshot (KernelExtra.TH32CS_SNAPPROCESS, new DWORD(0));
KernelExtra.PROCESSENTRY32.ByReference ent = new KernelExtra.PROCESSENTRY32.ByReference ();
if (!KernelExtra.INSTANCE.Process32First (hSnap, ent)) return result;
do {
if (ent.th32ParentProcessID.intValue () == pid) result.add (new Win32Process (ent.th32ProcessID.intValue ()));
} while (KernelExtra.INSTANCE.Process32Next (hSnap, ent));
Kernel32.INSTANCE.CloseHandle (hSnap);
return result;
}
此代码使用标准 JNA 库中未包含的以下 JNA 声明:
public interface KernelExtra extends StdCallLibrary {
/**
* Includes all heaps of the process specified in th32ProcessID in the snapshot. To enumerate the heaps, see
* Heap32ListFirst.
*/
WinDef.DWORD TH32CS_SNAPHEAPLIST = new WinDef.DWORD(0x00000001);
/**
* Includes all processes in the system in the snapshot. To enumerate the processes, see Process32First.
*/
WinDef.DWORD TH32CS_SNAPPROCESS = new WinDef.DWORD(0x00000002);
/**
* Includes all threads in the system in the snapshot. To enumerate the threads, see Thread32First.
*/
WinDef.DWORD TH32CS_SNAPTHREAD = new WinDef.DWORD(0x00000004);
/**
* Includes all modules of the process specified in th32ProcessID in the snapshot. To enumerate the modules, see
* Module32First. If the function fails with ERROR_BAD_LENGTH, retry the function until it succeeds.
*/
WinDef.DWORD TH32CS_SNAPMODULE = new WinDef.DWORD(0x00000008);
/**
* Includes all 32-bit modules of the process specified in th32ProcessID in the snapshot when called from a 64-bit
* process. This flag can be combined with TH32CS_SNAPMODULE or TH32CS_SNAPALL. If the function fails with
* ERROR_BAD_LENGTH, retry the function until it succeeds.
*/
WinDef.DWORD TH32CS_SNAPMODULE32 = new WinDef.DWORD(0x00000010);
/**
* Includes all processes and threads in the system, plus the heaps and modules of the process specified in th32ProcessID.
*/
WinDef.DWORD TH32CS_SNAPALL = new WinDef.DWORD((TH32CS_SNAPHEAPLIST.intValue() |
TH32CS_SNAPPROCESS.intValue() | TH32CS_SNAPTHREAD.intValue() | TH32CS_SNAPMODULE.intValue()));
/**
* Indicates that the snapshot handle is to be inheritable.
*/
WinDef.DWORD TH32CS_INHERIT = new WinDef.DWORD(0x80000000);
/**
* Describes an entry from a list of the processes residing in the system address space when a snapshot was taken.
*/
public static class PROCESSENTRY32 extends Structure {
public static class ByReference extends PROCESSENTRY32 implements Structure.ByReference {
public ByReference() {
}
public ByReference(Pointer memory) {
super(memory);
}
}
public PROCESSENTRY32() {
dwSize = new WinDef.DWORD(size());
}
public PROCESSENTRY32(Pointer memory) {
useMemory(memory);
read();
}
/**
* The size of the structure, in bytes. Before calling the Process32First function, set this member to
* sizeof(PROCESSENTRY32). If you do not initialize dwSize, Process32First fails.
*/
public WinDef.DWORD dwSize;
/**
* This member is no longer used and is always set to zero.
*/
public WinDef.DWORD cntUsage;
/**
* The process identifier.
*/
public WinDef.DWORD th32ProcessID;
/**
* This member is no longer used and is always set to zero.
*/
public BaseTSD.ULONG_PTR th32DefaultHeapID;
/**
* This member is no longer used and is always set to zero.
*/
public WinDef.DWORD th32ModuleID;
/**
* The number of execution threads started by the process.
*/
public WinDef.DWORD cntThreads;
/**
* The identifier of the process that created this process (its parent process).
*/
public WinDef.DWORD th32ParentProcessID;
/**
* The base priority of any threads created by this process.
*/
public WinDef.LONG pcPriClassBase;
/**
* This member is no longer used, and is always set to zero.
*/
public WinDef.DWORD dwFlags;
/**
* The name of the executable file for the process. To retrieve the full path to the executable file, call the
* Module32First function and check the szExePath member of the MODULEENTRY32 structure that is returned.
* However, if the calling process is a 32-bit process, you must call the QueryFullProcessImageName function to
* retrieve the full path of the executable file for a 64-bit process.
*/
public char[] szExeFile = new char[WinDef.MAX_PATH];
}
// the following methods are in kernel32.dll, but not declared there in the current version of Kernel32:
/**
* Takes a snapshot of the specified processes, as well as the heaps, modules, and threads used by these processes.
*
* @param dwFlags
* The portions of the system to be included in the snapshot.
*
* @param th32ProcessID
* The process identifier of the process to be included in the snapshot. This parameter can be zero to indicate
* the current process. This parameter is used when the TH32CS_SNAPHEAPLIST, TH32CS_SNAPMODULE,
* TH32CS_SNAPMODULE32, or TH32CS_SNAPALL value is specified. Otherwise, it is ignored and all processes are
* included in the snapshot.
*
* If the specified process is the Idle process or one of the CSRSS processes, this function fails and the last
* error code is ERROR_ACCESS_DENIED because their access restrictions prevent user-level code from opening them.
*
* If the specified process is a 64-bit process and the caller is a 32-bit process, this function fails and the
* last error code is ERROR_PARTIAL_COPY (299).
*
* @return
* If the function succeeds, it returns an open handle to the specified snapshot.
*
* If the function fails, it returns INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.
* Possible error codes include ERROR_BAD_LENGTH.
*/
public WinNT.HANDLE CreateToolhelp32Snapshot(WinDef.DWORD dwFlags, WinDef.DWORD th32ProcessID);
/**
* Retrieves information about the first process encountered in a system snapshot.
*
* @param hSnapshot A handle to the snapshot returned from a previous call to the CreateToolhelp32Snapshot function.
* @param lppe A pointer to a PROCESSENTRY32 structure. It contains process information such as the name of the
* executable file, the process identifier, and the process identifier of the parent process.
* @return
* Returns TRUE if the first entry of the process list has been copied to the buffer or FALSE otherwise. The
* ERROR_NO_MORE_FILES error value is returned by the GetLastError function if no processes exist or the snapshot
* does not contain process information.
*/
public boolean Process32First(WinNT.HANDLE hSnapshot, KernelExtra.PROCESSENTRY32.ByReference lppe);
/**
* Retrieves information about the next process recorded in a system snapshot.
*
* @param hSnapshot A handle to the snapshot returned from a previous call to the CreateToolhelp32Snapshot function.
* @param lppe A pointer to a PROCESSENTRY32 structure.
* @return
* Returns TRUE if the next entry of the process list has been copied to the buffer or FALSE otherwise. The
* ERROR_NO_MORE_FILES error value is returned by the GetLastError function if no processes exist or the snapshot
* does not contain process information.
*/
public boolean Process32Next(WinNT.HANDLE hSnapshot, KernelExtra.PROCESSENTRY32.ByReference lppe);
}
然后您可以使用“getChildren()”方法获取子项列表,终止父项,然后递归地终止子项。
我相信您可以使用反射来增加 java.lang.Process 的 PID(不过,我还没有这样做;我转而使用 Win32 API 自己创建进程,这样我就可以更好地控制它) .
所以把它放在一起,你需要这样的东西:
int pid = (some code to extract PID from the process you want to kill);
Win32Process process = new Win32Process(pid);
kill(process);
public void kill(Win32Process target) throws IOException
{
List<Win32Process> children = target.getChildren ();
target.terminateProcess ();
for (Win32Process child : children) kill(child);
}
事实证明,Java API 的这一特殊缺点已在 Java 9 中得到修复。请参阅 Java 9 文档的预览 here (如果没有加载正确的页面,您需要查看 java.lang.ProcessHandle
接口(interface))。对于上述问题的要求,代码现在看起来像这样:
Process child = ...;
kill (child.toHandle());
public void kill (ProcessHandle handle)
{
handle.descendants().forEach((child) -> kill(child));
handle.destroy();
}
(请注意,这还没有经过测试——我还没有切换到 Java 9,但正在积极阅读它)
关于java - 如何终止进程树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10124299/
我是 Linux 的新手,并且继承了保持我们的单一 Linux 服务器运行的职责。这是我们的SVN服务器,所以比较重要。 原来在我之前维护它的人有一个 cron 任务,当有太多 svnserve 进程
Node 虽然自身存在多个线程,但是运行在 v8 上的 JavaScript 是单线程的。Node 的 child_process 模块用于创建子进程,我们可以通过子进程充分利用 CPU。范例:
Jenkins 有这么多进程处于事件状态是否正常? 我检查了我的设置,我只配置了 2 个“执行者”... htop http://d.pr/i/RZzG+ 最佳答案 您不仅要限制 Master 中的执
我正在尝试在 scala 中运行这样的 bash 命令: cat "example file.txt" | grep abc Scala 有一个特殊的流程管道语法,所以这是我的第一个方法: val f
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
我需要一些帮助来理解并发编程的基础知识。事实上,我读得越多,就越感到困惑。因此,我理解进程是顺序执行的程序的一个实例,并且它可以由一个或多个线程组成。在单核CPU中,一次只能执行一个线程,而在多核CP
我的问题是在上一次集成测试后服务器进程没有关闭。 在integration.rs中,我有: lazy_static! { static ref SERVER: Arc> = {
我正在使用 Scala scala.sys.process图书馆。 我知道我可以用 ! 捕获退出代码和输出 !!但是如果我想同时捕获两者呢? 我看过这个答案 https://stackoverflow
我正在开发一个C++类(MyClass.cpp),将其编译为动态共享库(MyClass.so)。 同一台Linux计算机上运行的两个不同应用程序将使用此共享库。 它们是两个不同的应用程序。它不是多线程
我在我的 C 程序中使用 recvfrom() 从多个客户端接收 UDP 数据包,这些客户端可以使用自定义用户名登录。一旦他们登录,我希望他们的用户名与唯一的客户端进程配对,这样服务器就可以通过数据包
如何更改程序,以便函数 function_delayed_1 和 function_delayed_2 仅同时执行一次: int main(int argc, char *argv[]) {
考虑这两个程序: //in #define MAX 50 int main(int argc, char* argv[]) { int *count; int fd=shm
请告诉我如何一次打开三个终端,这样我的项目就可以轻松执行,而不必打开三个终端三次然后运行三个exe文件。请问我们如何通过脚本来做到这一点,即打开三个终端并执行三个 exe 文件。 最佳答案 在后台运行
我编写了一个监控服务来跟踪一组进程,并在服务行为异常、内存使用率高、超出 CPU 运行时间等时发出通知。 这在我的本地计算机上运行良好,但我需要它指向远程机器并获取这些机器上的进程信息。 我的方法,在
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 想改进这个问题?将问题更新为 on-topic对于堆栈溢出。 8年前关闭。 Improve this qu
我有一个允许用户上传文件的应用程序。上传完成后,必须在服务器上完成许多处理步骤(解压、存储、验证等...),因此稍后会在一切完成后通过电子邮件通知用户。 我见过很多示例,其中 System.Compo
这个问题对很多人来说可能听起来很愚蠢,但我想对这个话题有一个清晰的理解。例如:当我们在 linux(ubuntu, x86) 上构建一个 C 程序时,它会在成功编译和链接过程后生成 a.out。 a.
ps -eaf | grep java 命令在这里不是识别进程是否是 java 进程的解决方案,因为执行此命令后我的许多 java 进程未在输出中列出。 最佳答案 简答(希望有人写一个更全面的): 获
我有几个与内核态和用户态的 Windows 进程相关的问题。 如果我有一个 hello world 应用程序和一个暴露新系统调用 foo() 的 hello world 驱动程序,我很好奇在内核模式下
我找不到很多关于 Windows 中不受信任的完整性级别的信息,对此有一些疑问: 是否有不受信任的完整性级别进程可以创建命名对象的地方? (互斥锁、事件等) 不受信任的完整性级别进程是否应该能够打开一
我是一名优秀的程序员,十分优秀!