") I need to execute a tcl file that gives an exit, we st...">

ID of the Gwt process that is executed using the runtime.getExec function ("<tcl file>")

I need to execute a tcl file that gives an exit, we stop the process from java. So I am using

Process proc = Runtime.getRuntime().exec("< tcl file >");

      

I need to get the process id (PID) to stop the process. I can run the same tcl file multiple times, so I cannot get the pid using get the name of the executable. Give me some ways to get process id using JAVA when running external program.

ps command output:

25014 pts / 0 00:00:00 tclfile
29998 pts / 0 00:00:09 tclfile
30866 pts / 0 00:00:00 tclfile

Each copy is different. I only need to stop the specified process at a time, cannot complete everything with killall -9 tclfile command.

+3


source to share


2 answers


pid is unaffected by Java because Java is platform agnostic and pids are platform specific. So you can't get the actual pid without using your own code, sorry.

But if you just want to handle a child process that you can kill later, you can do it in pure Java. The object Process

has methods destroy()

(which kills the process) and waitFor()

(which waits for it to exit). In Java, there are also 8 isAlive()

and destroyForcibly()

methods
.



OK, after searching the net to find the source code for ProcessImpl

in different JREs, it looks like on Windows ProcessImpl

there is a field that is presumably the Win32 handle returned , and on Linux there is a field that is represented by the process ID. If you want to be really hacky (and unsupported and potentially tied to a specific JDK implementation, etc. - all the usual caveats apply), you can potentially access these fields if you want. handle

CreateProcess

UNIXProcess

pid

However, a better solution would be to write your own code yourself, or pipe it to a helper process (like in bash, as Donal Fellows answer).

+1


source


You cannot get a process ID from an object Process

; it knows it (strictly, it is known to an object within a class that is not part of the public API), but it won't tell you. The simplest way to get the PID is to have the subprocess tell you about this value by writing it in standard (or standard error, but less common) as its first action. Then you can just read the string, print an integer out of it, and there you go.

Getting Tcl scripts to print PIDs is trivial. Just enter this line:

puts [pid]
# Or: puts stdout [pid]

      



If you cannot change the Tcl script, you can use a shell script trick to wrap it in whatever writes the value:

#!/bin/sh
echo $$
# exec, in bash, *replaces* the process implementation with another program
exec tclsh "$@"

      

+1


source







All Articles