import processing.serial.*;
import processing.sound.*;
SoundFile file;
Serial myPort; // Create object from Serial class
String val; // Data received from the serial port
//String antwoord = "A";
void setup()
{
size(300,300);
// I know that the first port in the serial list on my mac
// is Serial.list()[0].
// On Windows machines, this generally opens COM1.
// Open whatever port is the one you're using.
String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
myPort = new Serial(this, portName, 9600);
}
void draw()
{
if ( myPort.available() > 0)
{ // If data is available,
val = trim( myPort.readStringUntil(ENTER) );
// read it and store it in val
}
//println(val); //print it out in the console
file = new SoundFile(this,"Promise.mp3");
if ("A".equals(val) == true && file.isPlaying() == false) {
file.play();
file.amp(0.2);}
else{
ellipse(40,40,40,40);
}
}
I got this code, but I want the sound to keep playing as long as the signal 'A' is given. Now it starts playing constantly, which leads to a weird static noise. How can I make it just play steadidly?
You're creating a new SoundFile in every run of draw. So file.isPlaying() will always return false. Only create a new SoundFile if you haven't already. The simplest solution is probably to move file = new SoundFile(this,"Promise.mp3"); into setup
Or you check or remember if you already loaded the file.
I am sorry if it is a bit disconnected but I recommend using minim or a different sound library instead of the processing one, since it causes a lot of problems in exporting (at least it had done so consistently for me).
I am working on a sample project in unity android where application reads a textfile in an OTG pen drive connected to the android phone, the problem is my code works fine in some devices but it doesn't work in some devices. I am unable to figure out the main cause even through the logcat extreme as it doesn't throw any error at all that specifies code error.
I tried adding text logs to print text in between the code to see which texts are not printed, which would further tell me that after which line code stopped working but all the texts are printed.
This is my code that detects the USB and returns true if a text file is present in USB:
public void LocateFile()
{
textfileData = null;
using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
using (AndroidJavaObject context = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
{
// Get all available external file directories (emulated and USBdrives)
AndroidJavaObject[] externalFilesDirectories = context.Call<AndroidJavaObject[]>("getExternalFilesDirs", (object)null);
AndroidJavaObject emulated = null;
AndroidJavaObject USBdrive = null;
for (int i = 0; i < externalFilesDirectories.Length; i++)
{
AndroidJavaObject directory = externalFilesDirectories[i];
using (AndroidJavaClass environment = new AndroidJavaClass("android.os.Environment"))
{
bool isRemovable = environment.CallStatic<bool>("isExternalStorageRemovable", directory);
bool isEmulated = environment.CallStatic<bool>("isExternalStorageEmulated", directory);
if (isEmulated)
{
emulated = directory;
}
else if (isRemovable && isEmulated == false)
{
USBdrive = directory;
}
}
}
// Return the USBdrive if available
if (USBdrive != null)
{
if (File.Exists(USBdrive.Call<string>("getAbsolutePath") + "/serial.txt"))
{
textfileData = File.ReadAllText(USBdrive.Call<string>("getAbsolutePath") + "/serial.txt");
}
}
}
}}
This code works on my android phone and returns true after detecting the file present in pendrive.
Can anyone tell me what could be the issue and point me in the right direction, I will greatly appreciate your support on this.
This locateFile() function is called on Update().
Update: I tried to debug the number of storage found in mobile and code is not reading the USB. It reads internal and SD storage perfectly.
Nokia 5 is the only phone the code has worked on so far but in 99% android devices GetExternalFilesDir is not reading usb storage.
Please someone tell me an alternate or how do I get this to work, it is very important.
My question is an extension on another question already answered, https://superuser.com/questions/257467/windows-7-how-to-pin-a-jar-to-the-taskbar
Is there a way to pin a jar to the taskbar, and have the window generated by the jar register as a different process, thus creating a different icon in the task bar? because as it stands, using any of the methods listed in the answer to the above question, you end up with a shortcut that can be pinned. but it is just a shortcut and only that, not the program itself. Im willing to try anything at this point as it is beginning to be very bothersome. not only does it look unprofessional, it uses up unnecessary screen real estate. As I know someone is going to ask what else I've tried, here's a bit of code i tried to run in c# to launch the jar, but of course, it does the same thing, registering the new process as a new process. (should have thought that one through.)
string strCmdText;
strCmdText = "-jar ImgurDownloader.jar";
Process process = new Process();
process.StartInfo.Arguments = strCmdText;
process.StartInfo.FileName = "javaw";
process.StartInfo.UseShellExecute = false;
process.Start();
so then I tried this:
string strCmdText;
strCmdText = "-jar ImgurDownloader.jar";
Process process = Process.GetCurrentProcess();
process.StartInfo.Arguments = strCmdText;
process.StartInfo.FileName = "javaw";
process.StartInfo.UseShellExecute = false;
process.Start();
and yet still, even if i try and replace the current process, it comes across as a new process, and thus a second icon in the taskbar. Please excuse my possibly short tone, the frustration is starting to kick in after a couple weeks.
Edit: have also tried setting the UAMID (User Application Model ID) using the JNA library to access shel32.dll's functions. The following is the code in the jar
public static void setCurrentProcessExplicitAppUserModelID(final String appID) {
if (SetCurrentProcessExplicitAppUserModelID(new WString(appID)).longValue() != 0)
throw new RuntimeException("unable to set current process explicit AppUserModelID to: " + appID);
}
public static String getCurrentProcessExplicitAppUserModelID() {
final PointerByReference r = new PointerByReference();
if (GetCurrentProcessExplicitAppUserModelID(r).longValue() == 0) {
final Pointer p = r.getValue();
return p.getString(0, true); // here we leak native memory by
// lazyness
}
return "N/A";
}
private static native NativeLong GetCurrentProcessExplicitAppUserModelID(PointerByReference appID);
private static native NativeLong SetCurrentProcessExplicitAppUserModelID(WString appID);
static {
Native.register("shell32");
}
then just call the set method. Tested with the get method, however,
NOTE: getCurrentProcessExplicitAppUserModelID is a lazy method and breaks things later on if used.
then in the C# Wrapper,
[DllImport("shell32.dll")]
public static extern int SetCurrentProcessExplicitAppUserModelID([MarshalAs(UnmanagedType.LPWStr)] string AppID);
static void Main()
{
int der = SetCurrentProcessExplicitAppUserModelID("MAndWorks.ImgurDownloader.ImgurDownloader.2.0.0.0");
string strCmdText;
Console.WriteLine(der);
strCmdText = "-jar ImgurDownloader.jar";
Process process = new Process();
process.StartInfo.Arguments = strCmdText;
process.StartInfo.FileName = "javaw";
process.StartInfo.UseShellExecute = false;
process.Start();
process.WaitForExit();
Console.WriteLine("AWFURA");
}
I am on Windows Seven 64-bit. I wrote a little application that uses RXTX to communication through serial port. I used the rxtxSerial.dll for Windows 64-bit and it works pretty well on both Eclispe and NetBeans.
At the root of the project, I placed RXTXComm.jar and rxtxSerial.dll.
The problem appears when I want to deploy the application. I used the Export function on Eclipse or I accessed the bin/ folder from NetBeans. I placed again RXTXComm.jar and rxtxSerial.dll at the root of the folders but when I execute the Application.jar, RXTX doesn't seem working. The scan seems to stay stuck whereas it shouldn't last more than a second.
[Sorry, I "need at least 10 reputation to post images."]
I tried all the suggestions I found on the internet:
installing the dlls and RXTXComm.jar in the JRE folder
placing the dlls in Windows32 folder
tried all the different export options of Export from Eclipse
I must be missing something. Has anyone already been successful in deploying RXTX for Windows 32/64bit and MAC? Could you describe what you did and what is necessary to do so?
Please find below the piece of code executing when scanning for ports:
private void scanButtonAction()
{
if(scanState == ST_FREE)
{
scanState = ST_SCANNING;
redrawComponents();
scan = new Thread(new ScanPorts());
scan.start();
}
}
// Thread run to scan the ports
private class ScanPorts implements Runnable {
public void run()
{
try
{
UARTConnection connection = new UARTConnection();
// listPort() is a long blocking call
String[][] list = connection.listPorts();
// Display the ports in the ComboBox
comboBoxModel.removeAllElements();
if(list.length == 0) comboBoxModel.addElement( new Item(-1, "No port scanned", "" ) );
else
{
for(int i = 0; i < list.length; i++)
{
// Id, Description (user's display), PortName (for serial connection)
comboBoxModel.addElement( new Item(i, list[i][1], list[i][0]) );
}
// To select the first item of the list. Necessary with custom Rendered
portNumberBox.setSelectedIndex(0);
}
scanState = ST_FREE;
redrawComponents();
// The connect button is enabled only after a first scan
connectButton.setEnabled(true);
}
catch(Exception ex)
{
scanState = ST_FREE;
redrawComponents();
}
}
}
public class UARTConnection {
public UARTConnection()
{
}
public String[][] listPorts() throws Exception
{
Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
Enumeration<CommPortIdentifier> tmpPortEnum = portEnum;
ArrayList<String[]> list = new ArrayList<String[]>();
int i = 0;
while ( portEnum.hasMoreElements() )
{
String port[] = new String[2];
CommPortIdentifier portIdentifier = portEnum.nextElement();
System.out.println(portIdentifier.getName() + " - " + getPortTypeName(portIdentifier.getPortType()));
port[0] = portIdentifier.getName();
port[1] = portIdentifier.getName() + " - " + getPortTypeName(portIdentifier.getPortType());
list.add(port);
i++;
}
String listOfPort[][] = new String[list.size()][2];
for(i = 0; i < list.size(); i++)
{
String[] port = list.get(i);
listOfPort[i][0] = port[0];
listOfPort[i][1] = port[1];
}
return listOfPort;
}
private String getPortTypeName ( int portType )
{
switch ( portType )
{
case CommPortIdentifier.PORT_I2C:
return "I2C";
case CommPortIdentifier.PORT_PARALLEL:
return "Parallel";
case CommPortIdentifier.PORT_RAW:
return "Raw";
case CommPortIdentifier.PORT_RS485:
return "RS485";
case CommPortIdentifier.PORT_SERIAL:
return "Serial";
default:
return "unknown type";
}
}
}
Thank you for your help.
I found the solution, for those it might help.
When running the application from Eclipse or NetBean, the app is running in 64-bit. Hence, I used the 64bit rxtxSerial.dll. It was working properly.
But I realized when running the compiled .jar outside of the IDE, the Windows process list was displaying javaw.exe *32 for the application. For some reason I ignore, the compiled .jar was in 32bit. Hence, the driver required was for Windows 32bit, not the 64bit. It works well from now on.
Note: in order to be able to work on my MAC, I had to compile the application in Java 1.6 (not 1.7) and to provide the MAC driver of course.
How do I get the id of my Java process?
I know there are several platform-dependent hacks, but I would prefer a more generic solution.
There exists no platform-independent way that can be guaranteed to work in all jvm implementations.
ManagementFactory.getRuntimeMXBean().getName() looks like the best (closest) solution, and typically includes the PID. It's short, and probably works in every implementation in wide use.
On linux+windows it returns a value like "12345#hostname" (12345 being the process id). Beware though that according to the docs, there are no guarantees about this value:
Returns the name representing the running Java virtual machine. The
returned name string can be any arbitrary string and a Java virtual
machine implementation can choose to embed platform-specific useful
information in the returned name string. Each running virtual machine
could have a different name.
In Java 9 the new process API can be used:
long pid = ProcessHandle.current().pid();
You could use JNA. Unfortunately there is no common JNA API to get the current process ID yet, but each platform is pretty simple:
Windows
Make sure you have jna-platform.jar then:
int pid = Kernel32.INSTANCE.GetCurrentProcessId();
Unix
Declare:
private interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary("c", CLibrary.class);
int getpid ();
}
Then:
int pid = CLibrary.INSTANCE.getpid();
Java 9
Under Java 9 the new process API can be used to get the current process ID. First you grab a handle to the current process, then query the PID:
long pid = ProcessHandle.current().pid();
Here's a backdoor method which might not work with all VMs but should work on both linux and windows (original example here):
java.lang.management.RuntimeMXBean runtime =
java.lang.management.ManagementFactory.getRuntimeMXBean();
java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm");
jvm.setAccessible(true);
sun.management.VMManagement mgmt =
(sun.management.VMManagement) jvm.get(runtime);
java.lang.reflect.Method pid_method =
mgmt.getClass().getDeclaredMethod("getProcessId");
pid_method.setAccessible(true);
int pid = (Integer) pid_method.invoke(mgmt);
Try Sigar . very extensive APIs. Apache 2 license.
private Sigar sigar;
public synchronized Sigar getSigar() {
if (sigar == null) {
sigar = new Sigar();
}
return sigar;
}
public synchronized void forceRelease() {
if (sigar != null) {
sigar.close();
sigar = null;
}
}
public long getPid() {
return getSigar().getPid();
}
The following method tries to extract the PID from java.lang.management.ManagementFactory:
private static String getProcessId(final String fallback) {
// Note: may fail in some JVM implementations
// therefore fallback has to be provided
// something like '<pid>#<hostname>', at least in SUN / Oracle JVMs
final String jvmName = ManagementFactory.getRuntimeMXBean().getName();
final int index = jvmName.indexOf('#');
if (index < 1) {
// part before '#' empty (index = 0) / '#' not found (index = -1)
return fallback;
}
try {
return Long.toString(Long.parseLong(jvmName.substring(0, index)));
} catch (NumberFormatException e) {
// ignore
}
return fallback;
}
Just call getProcessId("<PID>"), for instance.
For older JVM, in linux...
private static String getPid() throws IOException {
byte[] bo = new byte[256];
InputStream is = new FileInputStream("/proc/self/stat");
is.read(bo);
for (int i = 0; i < bo.length; i++) {
if ((bo[i] < '0') || (bo[i] > '9')) {
return new String(bo, 0, i);
}
}
return "-1";
}
Since Java 9 there is a method Process.getPid() which returns the native ID of a process:
public abstract class Process {
...
public long getPid();
}
To get the process ID of the current Java process one can use the ProcessHandle interface:
System.out.println(ProcessHandle.current().pid());
You can check out my project: JavaSysMon on GitHub. It provides process id and a bunch of other stuff (CPU usage, memory usage) cross-platform (presently Windows, Mac OSX, Linux and Solaris)
java.lang.management.ManagementFactory.getRuntimeMXBean().getName().split("#")[0]
In Scala:
import sys.process._
val pid: Long = Seq("sh", "-c", "echo $PPID").!!.trim.toLong
This should give you a workaround on Unix systems until Java 9 will be released.
(I know, the question was about Java, but since there is no equivalent question for Scala, I wanted to leave this for Scala users who might stumble into the same question.)
For completeness there is a wrapper in Spring Boot for the
String jvmName = ManagementFactory.getRuntimeMXBean().getName();
return jvmName.split("#")[0];
solution. If an integer is required, then this can be summed up to the one-liner:
int pid = Integer.parseInt(ManagementFactory.getRuntimeMXBean().getName().split("#")[0]);
If someone uses Spring boot already, she/he might use org.springframework.boot.ApplicationPid
ApplicationPid pid = new ApplicationPid();
pid.toString();
The toString() method prints the pid or '???'.
Caveats using the ManagementFactory are discussed in other answers already.
public static long getPID() {
String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
if (processName != null && processName.length() > 0) {
try {
return Long.parseLong(processName.split("#")[0]);
}
catch (Exception e) {
return 0;
}
}
return 0;
}
I am adding this, in addition to other solutions.
with Java 10, to get process id
final RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
final long pid = runtime.getPid();
out.println("Process ID is '" + pid);
The latest I have found is that there is a system property called sun.java.launcher.pid that is available at least on linux. My plan is to use that and if it is not found to use the JMX bean.
It depends on where you are looking for the information from.
If you are looking for the information from the console you can use the jps command. The command gives output similar to the Unix ps command and comes with the JDK since I believe 1.5
If you are looking from the process the RuntimeMXBean (as said by Wouter Coekaerts) is probably your best choice. The output from getName() on Windows using Sun JDK 1.6 u7 is in the form [PROCESS_ID]#[MACHINE_NAME]. You could however try to execute jps and parse the result from that:
String jps = [JDK HOME] + "\\bin\\jps.exe";
Process p = Runtime.getRuntime().exec(jps);
If run with no options the output should be the process id followed by the name.
This is the code JConsole, and potentially jps and VisualVM uses. It utilizes classes from
sun.jvmstat.monitor.* package, from tool.jar.
package my.code.a003.process;
import sun.jvmstat.monitor.HostIdentifier;
import sun.jvmstat.monitor.MonitorException;
import sun.jvmstat.monitor.MonitoredHost;
import sun.jvmstat.monitor.MonitoredVm;
import sun.jvmstat.monitor.MonitoredVmUtil;
import sun.jvmstat.monitor.VmIdentifier;
public class GetOwnPid {
public static void main(String[] args) {
new GetOwnPid().run();
}
public void run() {
System.out.println(getPid(this.getClass()));
}
public Integer getPid(Class<?> mainClass) {
MonitoredHost monitoredHost;
Set<Integer> activeVmPids;
try {
monitoredHost = MonitoredHost.getMonitoredHost(new HostIdentifier((String) null));
activeVmPids = monitoredHost.activeVms();
MonitoredVm mvm = null;
for (Integer vmPid : activeVmPids) {
try {
mvm = monitoredHost.getMonitoredVm(new VmIdentifier(vmPid.toString()));
String mvmMainClass = MonitoredVmUtil.mainClass(mvm, true);
if (mainClass.getName().equals(mvmMainClass)) {
return vmPid;
}
} finally {
if (mvm != null) {
mvm.detach();
}
}
}
} catch (java.net.URISyntaxException e) {
throw new InternalError(e.getMessage());
} catch (MonitorException e) {
throw new InternalError(e.getMessage());
}
return null;
}
}
There are few catches:
The tool.jar is a library distributed with Oracle JDK but not JRE!
You cannot get tool.jar from Maven repo; configure it with Maven is a bit tricky
The tool.jar probably contains platform dependent (native?) code so it is not easily
distributable
It runs under assumption that all (local) running JVM apps are "monitorable". It looks like
that from Java 6 all apps generally are (unless you actively configure opposite)
It probably works only for Java 6+
Eclipse does not publish main class, so you will not get Eclipse PID easily
Bug in MonitoredVmUtil?
UPDATE: I have just double checked that JPS uses this way, that is Jvmstat library (part of tool.jar). So there is no need to call JPS as external process, call Jvmstat library directly as my example shows. You can aslo get list of all JVMs runnin on localhost this way.
See JPS source code:
I know this is an old thread, but I wanted to call out that API for getting the PID (as well as other manipulation of the Java process at runtime) is being added to the Process class in JDK 9: http://openjdk.java.net/jeps/102
Based on Ashwin Jayaprakash's answer (+1)
about the Apache 2.0 licensed SIGAR, here is how I use it to get only the PID of the current process:
import org.hyperic.sigar.Sigar;
Sigar sigar = new Sigar();
long pid = sigar.getPid();
sigar.close();
Even though it does not work on all platforms, it does work on Linux, Windows, OS X and various Unix platforms as listed here.
You can try getpid() in JNR-Posix.
It has a Windows POSIX wrapper that calls getpid() off of libc.
I found a solution that may be a bit of an edge case and I didn't try it on other OS than Windows 10, but I think it's worth noticing.
If you find yourself working with J2V8 and nodejs, you can run a simple javascript function returning you the pid of the java process.
Here is an example:
public static void main(String[] args) {
NodeJS nodeJS = NodeJS.createNodeJS();
int pid = nodeJS.getRuntime().executeIntegerScript("process.pid;\n");
System.out.println(pid);
nodeJS.release();
}
Here is my solution:
public static boolean isPIDInUse(int pid) {
try {
String s = null;
int java_pid;
RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
java_pid = Integer.parseInt(rt.getName().substring(0, rt.getName().indexOf("#")));
if (java_pid == pid) {
System.out.println("In Use\n");
return true;
}
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
return false;
}
This is what I used when I had similar requirement. This determines the PID of the Java process correctly. Let your java code spawn a server on a pre-defined port number and then execute OS commands to find out the PID listening on the port. For Linux
netstat -tupln | grep portNumber