How to use createAttachFile method of sun.tools.attach.LinuxVirtualMachine class

Best Powermock code snippet using sun.tools.attach.LinuxVirtualMachine.createAttachFile

Source:LinuxVirtualMachine.java Github

copy

Full Screen

...52 // attach mechanism in the target VM by sending it a QUIT signal.53 // Then we attempt to find the socket file again.54 path = findSocketFile(pid);55 if (path == null) {56 File f = createAttachFile(pid);57 try {58 // On LinuxThreads each thread is a process and we don't have the59 // pid of the VMThread which has SIGQUIT unblocked. To workaround60 // this we get the pid of the "manager thread" that is created61 // by the first call to pthread_create. This is parent of all62 // threads (except the initial thread).63 if (isLinuxThreads) {64 int mpid = getLinuxThreadsManager(pid);65 assert mpid >= 1;66 sendQuitToChildrenOf(mpid);67 }68 else {69 sendQuitTo(pid);70 }71 // give the target VM time to start the attach mechanism72 int i = 0;73 long delay = 200;74 int retries = (int) (attachTimeout() / delay);75 do {76 try {77 Thread.sleep(delay);78 }79 catch (InterruptedException ignore) { }80 path = findSocketFile(pid);81 i++;82 }83 while (i <= retries && path == null);84 if (path == null) {85 throw new AttachNotSupportedException(86 "Unable to open socket file: target process not responding " +87 "or HotSpot VM not loaded");88 }89 }90 finally {91 f.delete();92 }93 }94 // Check that the file owner/permission to avoid attaching to95 // bogus process96 checkPermissions(path);97 // Check that we can connect to the process98 // - this ensures we throw the permission denied error now rather than99 // later when we attempt to enqueue a command.100 int s = socket();101 try {102 connect(s, path);103 }104 finally {105 close(s);106 }107 }108 /**109 * Detach from the target VM.110 */111 @Override112 public void detach()113 {114 synchronized (this) {115 if (path != null) {116 path = null;117 }118 }119 }120 // protocol version121 private static final String PROTOCOL_VERSION = "1";122 // known errors123 private static final int ATTACH_ERROR_BADVERSION = 101;124 /**125 * Execute the given command in the target VM.126 */127 @Override128 InputStream execute(String cmd, Object... args) throws AgentLoadException, IOException129 {130 assert args.length <= 3; // includes null131 // did we detach?132 String p;133 synchronized (this) {134 if (path == null) {135 throw new IOException("Detached from target VM");136 }137 p = path;138 }139 // create UNIX socket140 int s = socket();141 // connect to target VM142 try {143 connect(s, p);144 }145 catch (IOException x) {146 close(s);147 throw x;148 }149 IOException ioe = null;150 // connected - write request151 // <ver> <cmd> <args...>152 try {153 writeString(s, PROTOCOL_VERSION);154 writeString(s, cmd);155 for (int i = 0; i < 3; i++) {156 if (i < args.length && args[i] != null) {157 writeString(s, (String) args[i]);158 }159 else {160 writeString(s, "");161 }162 }163 }164 catch (IOException x) {165 ioe = x;166 }167 // Create an input stream to read reply.168 SocketInputStream sis = new SocketInputStream(s);169 // Read the command completion status.170 int completionStatus;171 try {172 completionStatus = readInt(sis);173 }174 catch (IOException x) {175 sis.close();176 if (ioe != null) {177 throw ioe;178 }179 else {180 throw x;181 }182 }183 if (completionStatus != 0) {184 sis.close();185 // In the event of a protocol mismatch then the target VM186 // returns a known error so that we can throw a reasonable error.187 if (completionStatus == ATTACH_ERROR_BADVERSION) {188 throw new IOException("Protocol mismatch with target VM");189 }190 // Special-case the "load" command so that the right exception is thrown.191 if ("load".equals(cmd)) {192 throw new AgentLoadException("Failed to load agent library");193 }194 else {195 throw new IOException("Command failed in target VM");196 }197 }198 // Return the input stream so that the command output can be read.199 return sis;200 }201 /**202 * InputStream for the socket connection to get target VM.203 */204 private final class SocketInputStream extends InputStream205 {206 int s;207 SocketInputStream(int s)208 {209 this.s = s;210 }211 @Override212 public synchronized int read() throws IOException213 {214 byte[] b = new byte[1];215 int n = read(b, 0, 1);216 if (n == 1) {217 return b[0] & 0xff;218 }219 else {220 return -1;221 }222 }223 @Override224 public synchronized int read(byte[] bs, int off, int len) throws IOException225 {226 if (off < 0 || off > bs.length || len < 0 || off + len > bs.length || off + len < 0) {227 throw new IndexOutOfBoundsException();228 }229 else if (len == 0) {230 return 0;231 }232 return LinuxVirtualMachine.read(s, bs, off, len);233 }234 @Override235 public void close() throws IOException236 {237 LinuxVirtualMachine.close(s);238 }239 }240 // Return the socket file for the given process.241 // Checks working directory of process for .java_pid<pid>. If not242 // found it looks in /tmp.243 private String findSocketFile(int pid)244 {245 // First check for a .java_pid<pid> file in the working directory246 // of the target process247 String fn = ".java_pid" + pid;248 String path = "/proc/" + pid + "/cwd/" + fn;249 File f = new File(path);250 if (!f.exists()) {251 // Not found, so try /tmp252 path = "/tmp/" + fn;253 f = new File(path);254 if (!f.exists()) {255 return null; // not found256 }257 }258 return path;259 }260 // On Solaris/Linux a simple handshake is used to start the attach mechanism261 // if not already started. The client creates a .attach_pid<pid> file in the262 // target VM's working directory (or /tmp), and the SIGQUIT handler checks263 // for the file.264 private File createAttachFile(int pid) throws IOException265 {266 String fn = ".attach_pid" + pid;267 String path = "/proc/" + pid + "/cwd/" + fn;268 File f = new File(path);269 try {270 f.createNewFile();271 }272 catch (IOException ignore) {273 path = "/tmp/" + fn;274 f = new File(path);275 f.createNewFile();276 }277 return f;278 }...

Full Screen

Full Screen

createAttachFile

Using AI Code Generation

copy

Full Screen

1import java.io.File;2import java.io.IOException;3import java.lang.management.ManagementFactory;4import java.lang.management.RuntimeMXBean;5import java.lang.reflect.Method;6import java.util.List;7public class AttachFileTest {8 public static void main(String[] args) throws Exception {9 RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();10 String name = runtimeMXBean.getName();11 int index = name.indexOf('@');12 String pid = name.substring(0, index);13 String attachFile = getAttachFile(pid);14 System.out.println("attach file: " + attachFile);15 createAttachFile(attachFile);16 }17 private static String getAttachFile(String pid) throws IOException {18 String path = "/tmp";19 if (System.getProperty("os.name").toLowerCase().contains("windows")) {20 path = System.getenv("TEMP");21 }22 return path + File.separator + ".java_pid" + pid;23 }24 private static void createAttachFile(String attachFile) throws Exception {25 Class<?> clazz = Class.forName("sun.tools.attach.LinuxVirtualMachine");26 Method method = clazz.getDeclaredMethod("createAttachFile", String.class);27 method.setAccessible(true);28 method.invoke(null, attachFile);29 }30}31ProcessHandle currentProcess = ProcessHandle.current();32long pid = currentProcess.pid();33ProcessHandle currentProcess = ProcessHandle.current();34long pid = currentProcess.pid();35ProcessHandle currentProcess = ProcessHandle.current();36long pid = currentProcess.pid();

Full Screen

Full Screen

createAttachFile

Using AI Code Generation

copy

Full Screen

1import sun.tools.attach.LinuxVirtualMachine;2import java.io.File;3import java.io.FileWriter;4import java.io.IOException;5import java.io.PrintWriter;6import java.io.BufferedReader;7import java.io.InputStreamReader;8import java.io.InputStream;9import java.io.FileInputStream;10import java.io.FileOutputStream;11import java.io.OutputStream;12import java.io.BufferedOutputStream;13import java.util.Arrays;14import java.util.List;15import java.util.ArrayList;16import java.util.Map;17import java.util.HashMap;18import java.util.Set;19import java.util.HashSet;20import java.util.Iterator;21import java.util.regex.Pattern;22import java.util.regex.Matcher;23import java.util.Date;24import java.text.SimpleDateFormat;25import java.util.TimeZone;26import java.util.concurrent.TimeUnit;27import java.util.concurrent.TimeoutException;28import java.util.concurrent.Executors;29import java.util.concurrent.ExecutorService;30import java.util.concurrent.Callable;31import java.util.concurrent.Future;32class ExecuteCommand implements Callable<String> {33 String command = "";34 String output = "";35 Process process = null;36 BufferedReader reader = null;37 InputStream in = null;38 String line = "";39 StringBuilder sb = new StringBuilder();40 public ExecuteCommand(String command) {41 this.command = command;42 }43 public String call() throws Exception {44 try {45 process = Runtime.getRuntime().exec(command);46 in = process.getInputStream();47 reader = new BufferedReader(new InputStreamReader(in));48 while ((line = reader.readLine()) != null) {49 sb.append(line);50 sb.append("51");52 }53 output = sb.toString();54 } catch (IOException e) {55 System.out.println("Exception: " + e);56 } finally {57 if (reader != null) {58 try {59 reader.close();60 } catch (IOException e) {61 System.out.println("Exception: " + e);62 }63 }64 if (in != null) {65 try {66 in.close();67 } catch (IOException e) {68 System.out.println("Exception: " + e);69 }70 }71 if (process != null) {72 try {73 process.destroy();74 } catch (Exception e) {75 System.out.println("Exception: " + e);76 }77 }78 }79 return output;80 }81}82class ExecuteCommandWithTimeout implements Callable<String> {83 String command = "";

Full Screen

Full Screen

createAttachFile

Using AI Code Generation

copy

Full Screen

1import sun.tools.attach.LinuxVirtualMachine;2import java.io.File;3public class TestCreateAttachFile {4 public static void main(String[] args) {5 try {6 String pid = args[0];7 String fileName = args[1];8 LinuxVirtualMachine vm = (LinuxVirtualMachine) LinuxVirtualMachine.attach(pid);9 vm.createAttachFile(new File(fileName));10 vm.detach();11 } catch (Exception e) {12 e.printStackTrace();13 }14 }15}

Full Screen

Full Screen

createAttachFile

Using AI Code Generation

copy

Full Screen

1import java.io.*;2import java.lang.management.ManagementFactory;3import java.lang.management.ThreadInfo;4import java.lang.management.ThreadMXBean;5import java.lang.reflect.Method;6import java.util.ArrayList;7import java.util.List;8import java.util.Properties;9import java.util.concurrent.TimeUnit;10public class Attach {11 public static void main(String[] args) throws Exception {12 String pid = getPid();13 String name = getProcessName(pid);14 getHeapDump(pid, name);15 getThreadDump(pid, name);16 getCpuUsage(pid);17 getMemoryUsage(pid);18 }19 public static String getPid() throws IOException {20 String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];21 System.out.println("pid of this java process is: " + pid);22 return pid;23 }24 public static String getProcessName(String pid) throws IOException {25 String name = "";26 Process process = Runtime.getRuntime().exec("ps -p " + pid + " -o comm=");27 BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));28 String line;29 while ((line = br.readLine()) != null) {30 name = line;31 }32 System.out.println("name of this java process is: " + name);33 return name;34 }35 public static void getHeapDump(String pid, String name) throws Exception {36 Class<?> c = Class.forName("sun.tools.attach.LinuxVirtualMachine");37 Method attach = c.getDeclaredMethod("attach", String.class);38 Object vm = attach.invoke(null, pid);39 Method getHeapHump = c.getDeclaredMethod("getHeapHump", String.class);40 String heapDumpFile = name + ".hprof";41 getHeapHump.invoke(vm, heapDumpFile);42 System.out.println("heap dump file of this java process is: " + heapDumpFile);43 }

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Powermock automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful