I have following problem...I created a Process via ProcessBuilder in this way :
private ProcessBuilder processBuilder;
private Process process;
public void init() {
processBuilder = new ProcessBuilder(
"java", "-jar",
"bam.jar",
host,
);
processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
try {
process = processBuilder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
and I have function who should a kill process :
public void stop() {
process.destroy();
try {
process.waitFor(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (process.isAlive()) {
try {
Thread.sleep(5000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
process.destroyForcibly();
}
}
But killing process sometimes work, but sometimes doesn't work. Any idea?
had similar problem, resolved it by replacing processBuilder.start() with
java.lang.Process process = java.lang.Runtime.getRuntime().exec("command java -jar some.jar");
proccess.destroy();
Related
I am doing a small project for my girlfriends grandparents, that have a hard time using a computer so I thought I would be able to write something that might fix their problem. Here is the code first off:
import java.io.IOException;
public class OpenWordPad {
public static void main(String[] args) {
try {
System.out.println("Opening WordPad");
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec("wordpad");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Closing WordPad");
process.destroy();
} catch (IOException e) {
e.printStackTrace();
}
}
}
(had to indent some so sorry if it is a little wonky)
When I put notepad in the process line it works fine but when I put in wordpad it freaks out. I want to be able to open wordpad so I can put it on their computer. Any suggestions?
For that you can use runTime.exec("write"):
import java.io.IOException;
public class OpenWordPad {
public static void main(String[] args) {
try {
System.out.println("Opening WordPad");
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec("write"); // <--- here
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Closing WordPad");
process.destroy();
} catch (IOException e) {
e.printStackTrace();
}
}
}
opens WordPad.
I have a processbuilder that runs a .sh script. it opens a terminal. I want to destroy this terminal later. I tried process.destroy() but it did not do the job.
Code:
Process p = new ProcessBuilder("/usr/bin/gnome-terminal", "-e", "/home/omar/ros_ws/./baxter2.sh").start();
try {
Thread.sleep(10000); // wait for one second
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
p.destroy();
try
{
Process[] proc = new Process[2];
proc[0] = new ProcessBuilder("calc.exe").start();
proc[1] = new ProcessBuilder("notepad.exe").start();
try {
Thread.sleep(3000);
} catch (InterruptedException ex) {
}
proc[0].destroy();
proc[1].destroy();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
I want to do following operation in ordered wise
1. Stop jetty server
2. Delete used resource from jetty
3. Restart jetty server.
I have done this above using shutdownhook in java as below :
<code>
Thread restartThread = new Thread(){
public void run(){
try {
sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String osName = System.getProperty("os.name");
logger.debug("OS name:" + osName);
if (osName != null
&& osName.toUpperCase().startsWith("WINDOWS")) {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
List<String> cmdLine = new ArrayList<String>();
cmdLine.add("cmd.exe");
cmdLine.add("/C");
cmdLine.add("start");
cmdLine.add("\"\"");
cmdLine.add(getBaseDir() + File.separator + "restart.bat");
final ProcessBuilder pb = new ProcessBuilder(cmdLine);
Process process = pb.start();
if (process.exitValue() == 0) {
// after stopping server delete stores
deleteCertificates();
// restores files
restoreFiles(tmpdir, backupfilelist);
}
//p.waitFor();
} catch (IOException e) {
logger.error("Failed to restart:" + e.getMessage(), e);
}
}
});
System.exit(0);
} else {
try {
Runtime.getRuntime().exec("service appservice restart");
} catch (IOException e) {
logger.error("Failed to restart:" + e.getMessage(), e);
}
}
}
};
restartThread.start();
<code>
my concern is will it do it sequentially execution, otherwise application will fail to restore.
I have the following daemon that runs in a loop:
public class MyDaemon implements Daemon {
private Thread myThread;
private boolean stopped = false;
private DatagramChannel channel;
#Override
public void init(DaemonContext daemonContext) throws DaemonInitException,
Exception {
myThread = new Thread() {
#Override
public synchronized void start() {
MyDaemon.this.stopped = false;
super.start();
}
#Override
public void run() {
ByteBuffer buf = ByteBuffer.allocate(100);
while (!stopped) {
try {
channel.receive(buf);
String payload = buf;
ArrayList<Element> elements = buf.elements();
Message message = new Message();
message.setPayload();
message.setElements(elements);
DataManager controller = null;
try {
dm = new DataManager();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dm.saveMessage(message);
Thread.sleep(100);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
}
public static void main(String args[]) {
}
#Override
public void start() throws Exception {
channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(1400));
channel.configureBlocking(false);
myThread.start();
}
#Override
public void stop() throws Exception {
stopped = true;
try {
myThread.join(1000);
} catch (InterruptedException e) {
System.err.println(e.getMessage());
throw e;
}
}
#Override
public void destroy() {
myThread = null;
}
}
My data manager class simply looks like the following:
public class DataManager {
private static String insert = "insert into mytable "
+ “(payload, elementId, time)”
+ "values (?,?,?);”;
public Connection instantiateConnection() throws ClassNotFoundException,
SQLException {
Connection connection = DriverManager.getConnection("jdbc connection info”);
return connection;
}
public void saveMessage(Message message) {
try {
Connection connection = this.instantiateConnection();
connection.setAutoCommit(false);
PreparedStatement ps = connection.prepareStatement(insert);
for (Element element : message.getElements()) {
Timestamp time = new Timestamp(date.getTime());
ps.setString(1, message.getPayload());
ps.setString(2, element.getId());
ps.setTimestamp(3, time);
ps.addBatch();
}
ps.executeBatch();
connection.commit();
ps.close();
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Lastly, this is the ssh file that runs my daemon:
#!/bin/sh
# Setup variables EXEC=/usr/bin/jsvc
PID=/tmp/mydaemon.pid JAVA_HOME=/usr/lib/jvm/jre CLASS_PATH="/home/ec2-user/commons-daemon-1.0.15.jar”:”/MyDaemon.jar" CLASS=MyDaemon USER=ec2-user LOG_OUT=/tmp/mydaemon.out LOG_ERR=/mydaemon.err
do_exec() {
$EXEC -home "$JAVA_HOME" -cp $CLASS_PATH -user $USER -outfile $LOG_OUT -errfile $LOG_ERR -pidfile $PID $1 $CLASS }
case "$1" in
start)
do_exec
;;
stop)
do_exec "-stop"
;;
restart)
if [ -f "$PID" ]; then
do_exec "-stop"
do_exec
else
echo "service not running, will do nothing"
exit 1
fi
;;
*)
echo "usage: daemon {start|stop|restart}" >&2
exit 3
;; esac
This is a complete set of the code. Please help!
When this runs, the memory slowly grows until I get an out of memory exception.
Does anyone know what is leaking?
You are allocating the buffer inside each iteration of while loop. This is redundant and you dont need it as you are clearing the buffer at the end of the loop. Do this :
ByteBuffer buf = ByteBuffer.allocate(100);
while(!stopped)
{
// do something
buf.clear();
}
#Rembo Thanks a million! You were right on.
I added c3p0 connection pooling and I have been garbage collecting like a bum in january ever since.
What's the difference between running programs using java and run it using the command line? In the first case it does not work, but in the second case it works fine.
Java:
try {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("../../../my/prog \"//10.124.12.15/C:/output/*\" ../../../input/345 -N -A");
DataInputStream bis = new DataInputStream(proc.getInputStream());
int _byte;
while ((_byte = bis.read()) != -1)
System.out.print((char)_byte);
proc.waitFor();
} catch (IOException ex) {
ex.printStackTrace();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
AND command:
../../../my/prog "//10.124.12.15/C:/output/*" ../../../input/345 -N -A
Try using absolute path. Maybe that's your problem.
Thanks all, I solved my problem:
try {
String cmd="/progs/my/prog //10.124.12.15/C:/output/* /temp/input/345 -N -A"
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(
new String[]{"/usr/bin/bash", "-c", cmd, "1>/dev/null 2>&1"});
proc.waitFor();
} catch (IOException ex) {
ex.printStackTrace();
} catch (InterruptedException ex) {
ex.printStackTrace();
}