package org.jboss.fresh.shell.commands;
import org.jboss.fresh.io.BufferWriter;
import org.jboss.fresh.shell.AbstractExecutable;
import org.jboss.fresh.shell.Executable;
import org.jboss.fresh.shell.impl.Process;
import org.jboss.fresh.shell.impl.ShellImpl;
import org.jboss.fresh.shell.impl.SystemShellImpl;
import java.io.BufferedWriter;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;
// EX OK
public class KillExe extends AbstractExecutable {
private static transient org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(KillExe.class);
/**
Kills the process with the specified id
If no process is found with this id then a runtime exception is thrown.
*/
public void process(String exepath, String[] params) throws Exception {
log.debug("entered");
if (helpRequested() || params.length == 0) {
PrintWriter out = new PrintWriter(new BufferWriter(getStdOut()));
out.print("Usage: kill [-ex] [--help] [pid]\n");
out.print(" -<sig> : kind of signal (i.e. STOP, TERM, KILL)\n");
out.print(" pid : process id of the process to be 'killed'\n");
out.print(" --help : this help\n");
out.close();
log.debug("done");
return;
}
PrintWriter pout = new PrintWriter(new BufferedWriter(new BufferWriter(getStdOut())));
String sig = "TERM";
String pid = null;
// take one parameter: pid
for(int i=0; i<params.length; i++) {
String tmp = params[i];
if(tmp.startsWith("-")) {
sig = tmp.substring(1);
if(sig.length() == 0) {
error("You need to specify a signal name");
return;
}
} else {
pid = tmp;
}
}
if(pid == null) {
error("Process id not specified");
return;
}
Map m = ((ShellImpl) getShell()).getProcesses();
Process p = (Process) m.get(pid);
Executable ex = null;
if(p != null)
ex = p.getExecutable();
if (ex != null) {
ex.sendMessage(sig);
log.debug("done");
return;
}
m = ((SystemShellImpl) ((ShellImpl) getShell()).getSystemShell()).getProcMap();
p = (Process) m.get(pid);
if(p != null)
ex = p.getExecutable();
if (ex != null) {
ex.sendMessage(sig);
log.debug("done");
return;
}
Iterator it = m.entrySet().iterator();
while(it.hasNext()) {
Map.Entry ent = (Map.Entry) it.next();
String id = (String) ent.getKey();
if(match(id, pid)) {
p = (Process) ent.getValue();
if(p != null)
ex = p.getExecutable();
if (ex != null) {
ex.sendMessage(sig);
log.debug("done");
return;
} else {
break;
}
}
}
if (canThrowEx()) {
throw new RuntimeException("No process for id: " + pid);
} else {
pout.println("No process for id: " + pid);
pout.close();
log.debug("done");
return;
}
}
private boolean match(String id, String pid) {
int len = pid.length();
for(int i=0; i<len; i++) {
if(pid.charAt(i) != id.charAt(TRUNC_PAT[i]))
return false;
}
return true;
}
int [] TRUNC_PAT = new int [] {6, 7, 11, 12, 16, 17, 21, 22};
}