Sending a POSIX signal from the JVM - java

How do I send a POSIX signal from within the JVM? (in Java or Clojure)
I never thought this would be an issue until I tried googling it — there is lots of information about handling signals, but nothing about sending them.
Short of using the JNI or calling the shell to execute "kill", is there any other way to send a signal to a PID?

Ok. Answering myself: I looked at the suggested libraries, but I am wary of introducing new dependencies on lots of code, especially if I'll only use a small part of it.
It turns out the easiest way is to use JNA and interface with the system (libc) API. In clojure this pretty much amounts to:
(jna-invoke Integer kill pid signo)
after doing a (:use net.n01se.clojure-jna) of course.
Since this software is not intended to ever run on Windows, I'm fine with this solution which should work on all POSIX systems (MacOS and Linux are what I'm interested in).

POSIX signals is OS specific functions, but JVM is tried to be OS independent VM. So there are no standard functions for this.
But you can execute shell commands (using Runtime class) or use some lbrary for your needs, like a Posix for Java

Related

If it's "Write once run anywhere", why do so many Java programs tell me to pick the version for my OS?

I am fairly new to Java or programming in general. On my journeys through the internet to master this language I have come up the saying "write once run anywhere" multiple times.
But I have found many software that requires you to pick the right version for your OS. Sometimes there is only one version available.
Could you explain to me why that is so?
[expanded per the comments]
Java runs on a Virtual Machine, the JVM. In an ideal world this means that the Operating System is abstracted away behind this and you only have to make sure your code works with the JVM which will make it work with the underlying OS. This can already be undone by using the wrong path separators or line endings; it is not an absolute truth.
An application can use many Operating System-specific approaches/libraries/functions/etc that might make it not feasible to restrict yourself to one general codebase. Instead they might want to leverage some advantages provided by a platform and create a separate application with it.
The statement should probably be somewhere along the lines of "Write once in a general fashion, run anywhere" but that's not as snappy.
This statement is often linked to Java but there are also other languages that incorporate this: weblanguages like Javascript and HTML will run on any browser because the browser itself forms the abstraction between the language and the underlying OS.
Other languages don't have this (entirely?) since they work differently: C# will use the underlying .NET framework which as it is only exists for Windows. There exists a cross platform variant (Mono) but it would be an overstatement to consider C# truly cross platform.
The Java program or source code is compiled to generate "bytecodes" ( an intermediate binary format). Second, the bytecodes is executed by an interpreter which is part of the Java Virtual Machine (JVM).
"Write Once, Run Everywhere" refers to the fact that an application written is Java can be run on any hardware which has the Java Virtual Machine (JVM), and that the JVM is now licensed to hundreds of operating systems vendors systems including Microsoft for Windows.
Well, some stuff is really cross-platform (most of standard Java library), while some other stuff may need right version for the OS. Generally, this applies to software that uses dynamic libraries, that aren't written in Java. In this case, versions for different OSes are packed with libraries for this OS.
In case there's version only for one OS - it could be because required libraries don't exists for other OSes or developer didn't port it. There is still possibility that it's actually cross-platform, but developer tested it only under one OS.
Your question is more based on platform dependency/independency.
Java is a programming language which is platform independent which means the code which you write will produce the same output on all machines running Windows, Linus, Unix, etc... without any changes to the code. To run a Java program you need to have JVM (Java Virtual Machine) installed. Now what does JVM do.? Well, it translates your code into Machine code which the Operating System could understand. Therefore JVM is platform dependent since every OS has a different Machine code.
So, basically you write a Java Program only once and can be used/run everywhere.
you can write source code in one platform and run it any where.some times you can encounter problem if a new java version is available but still current version runs the code.

Bootable program

I'm a front end developer that's looking to get into some other languages such as Java or C++. I have an idea for a program and was just looking for an answer to something. What I would like to do is build a program and boot directly to that program. For example I have an old computer and I wipe the hard drive clean. So they is nothing currently on it. Not even an OS. I want to build a program that I can install to the hard drive that will boot straight into the program once started. Would this be considered an OS?
No you don't. Unless you want to spend many years, writing drivers for your graphics card, harddisk controller, usb controller, dma controller and all the other hardware your computer have.
What you want is a minimal operation system, which include just the kernel, and a runtime library and which start your program and nothing else on startup. A minimal Linux such as linux from scratch or bsd would be a good starting point.
First of all you need to decide your your program needs what. I mean should operate in Protected mode or the routine you have is tiny, so it is enough to run before entering protected mode (i.e. in real mode).
Here you can do three things
Modify bootloader to jump the execution to your code . Then Your code can resume normal os initialization.
Modify your os kernel early initialization code So that it executes your code before entering protected mode
I think your code will not be harmed if a bit of os portion is running. So you can write your routine before full kernel initialization.
Now note that for the later two point you need to modify your kernel, which is not easy (not even always possible)
Now the problem in first approach: Nothing will be ready for you, not even a regular c library or divice drivers , so you have to write every raw bit of code by hand which is crude.
This is off course not possible in java. Because the jvm will not be ready for you.
Now practically: there are lot of tiny os available, use one of them and modify as per your need. use this link to get a complete list of what is available for you.
First, Java is right out. You cannot possibly do this in Java without enormous amounts of tool-building. Java is not suited for this task at all.
You can do it in C++ or C. The search terms you are looking for is operating system development. This would probably not technically be considered developing an Operating System since it wouldn't run other programs, but the information about how to get through the boot-up procedure and establish a minimal environment are going to be most easily found in the category of operating system development. Some reasonable starting resources for that can be found at the OS Dev Wiki.
Alternately, you could take an existing small open-source OS and modify what it does after the boot-up sequence completes. If your program is intending to do anything more than just use the keyboard and the screen in text mode, there need to be device drivers. Thus, depending on the project, changing an existing OS may be the easiest route because you won't need to write your own device drivers for any devices you want to use.
Java can't run without Environment. If you want to run you program on you machine without OS, Java is a wrong choice.
C++ program can run without OS, but it's difficult to write a bootable program in C++.
If you want to write your own bootable program, you should use assembly for boot and load function, with some knowledge to use hardware in low level.
You have to have an operating system, so your program would be the operating system (or you would have to use another one and write it for that). It's certainly possible in C++, but it's not really possible to write an operating system in java.
Unless you want write something in (for example) Open Firmware and Forth or say a ROM BASIC. You'll probably qualify as a boot loader. Your application may qualify as an operating system. In my opinion, and a modern context, it entirely depends on how much functionality it provides to hosted applications. I'm not sure that something like FreeDOS would be considered an operating system (no pre-emptive task scheduling or GUI for example) given modern computers (I don't care to argue the point either way).

In C++ or Java is there a way to get the CPU usage?

I'd like to write a little program just to display the CPU usage as a percent, like the task manager does. I know intermediate C++ and Java. Is there a way to do this with either language? If so, perhaps a short example? I saw some page of a C++ command, but I couldn't make heads or tails of it.
I'm using Windows 7 on one computer and XP on the other. As for the multiple core response, I simply want to display the CPU usage percent as the task manager does, even with a multiple core processor.
double sysLoad = ManagementFactory.
getOperatingSystemMXBean().
getSystemLoadAverage();
does not work on every platform,
returns an average load of the past one minute
EDIT:
Recently found this one
http://sellmic.com/blog/2011/07/21/hidden-java-7-features-cpu-load-monitoring/
In Java 7 you can use com.sun.management package to get process load or system load.
usage:
OperatingSystemMXBean osBean = ManagementFactory
.getPlatformMXBean(com.sun.management.OperatingSystemMXBean.class);
// What % CPU load this current JVM is taking, from 0.0-1.0
System.out.println(osBean.getProcessCpuLoad());
// What % load the overall system is at, from 0.0-1.0
System.out.println(osBean.getSystemCpuLoad());
there are some system call functions provided in "windows.h", such as GetProcessorInfo(), CallNTPowerInformation(), GetTickCount(), QueryPerformanceFrequency(), QueryPerformanceCounter() and so on. You can google them, or find them in MSDN. I hope this answer can help you.
The answer is going to be platform specific, and differs between the Java and C++ cases. At some level you need to interface with OS specific APIs to extract the statistics. There are four possible approaches:
Call an appropriate external system monitoring command (system specific) and "scrape" the output of the command. You can do this from Java or C++.
In C++ (or using JNI / JNA in Java ... if you really have to), make calls on the OS-specific native APIs that provide the information used by the external system monitoring.
In Java, use some existing 3rd-party library that deals with the system specific JNI/JNA stuff. Possible examples include JavaSysMon and SIGAR ... though I can't make specific recommendations.
You could use the Java monitoring APIs ... but they don't provide enough information. You can get information about this processes resource usage, and the overall load average, but you can't get information about other processes.
Now the problem with all of the above (except, possibly, the last one) is that porting to a new platform requires work.
CPU usage is an operating system property, not a language property. The way to retrieve it would be specific to the OS you're using (which you fail to identify).
In addition, "CPU usage" is a very nebulous term anymore, with multiple cores, et al.
In Java you can do it using JavaSysMon
Assuming you're using Windows system, you can use Windows Management Instrumentation (WMI). It's powerful once you get it working. I never did it using Java. Of course, it's easier with C# .NET.
A good link is WMI info
If you try this, please tell me. I might be interested in helping you since this is also my interest.
IF you are using the Linux system, consider using shell scripting, like bash. The reason is shell scripting is powerful for operating system calls, like getting process ID and usage (pid command). And IT technicians are more comfortable with bash scripts than Java or C++.

Achieving multi-core in Java - how?

What is the easiest way in Java for achieving multi-core? And by this, I mean, to specifically point out on what core to execute some parts of the project, so good-old "normal" java threads are not an option.
So far, I was suggested JConqurr (which is an Eclipse toolkit for multi-core programming in java), JaMP (which extends Java for OpenMP), and MPJ express, of which I don't know much. Which of the above do you consider the best, or do you have other suggestions? It would be preferable to somehow mesure the performance boost/gain, but not exclusive.
Any help would be much appreciated.
Thanks,
twentynine.
Even though it is easy to write multi-threaded code in Java, there is nothing in the Java standard runtime which generically allow you to tell the JVM or the operating system how to schedule your program.
Hence you will need to have code specifically for your JVM and/or your operating system, and that code may not be doable in Java (unless you dive into JNI or JNA). External programs can pin processes to a CPU in many Unix versions (and probably Windows too), but I don't think you can do this for individual threads.
Scala is quite popular for this. It runs on the JVM and has bindings for Java to hook them together.

What is the best way to manage unix process from java?

I'm looking for some simple tasks like listing all the running process of a user, or kill a particular process by pid etc. Basic unix process management from Java. Is there a library out there that is relatively mature and documented? I could run a external command from the JVM and then parse the standard output/error but that seems like a lot of work and not robust at all. Any suggestions?
You will need to roll your own solution I think. Killing an external process created using the Process APIs can be done using Process.destroy(). (But note that destroy() as implemented on Linux / Unix does a "soft" kill, not a SIGKILL, so the external process may be able to avoid being killed.)
Anything beyond that is non-portable.
Listing processes (on a Linux machine) can be done by reading the /proc file system.
Other things can be done by calling a native command using Process. It depends on whether your management functionality requires use of syscalls that are not available to a "pure" Java program.
It is possible (in theory) to use JNI and native code to dig around in the JVM's native data structures to find the OS-level PID for the process and send it a signal.
If you go down the JNI + native library route, beware that native pointer problems and native threading issues can kill your JVM. You may also need to deal with building and distributing the native library for multiple architectures, etc. Also beware that the internal data structures are liable to be different for different JVM platforms, releases, etc, and that they are liable to change without notice.
I recommend JavaSysMon: You can list processes (pid, ppid, name and so on), kill processes (inclusive child processes) and monitor your computer. If you want to use it in a Maven project:
<dependency>
<groupId>javasysmon</groupId>
<artifactId>javasysmon</artifactId>
<version>0.3.3</version>
</dependency>
<repository>
<id>javasysmon-repo</id>
<url>http://openr66.free.fr/maven2/</url>
</repository>
You could try JNA Posix. If the appropriate functions aren't exported by that library, it's very easy to add support for them with JNA (I've done so for many Win32 APIs).
Here's a method to send SIGKILL to a process from Java. It use reflection to get the pid value from the Process subclass. Tested succesfully on Mac OS X 1.6 (Snow Leopard) and OpenSuse 11.4, java 1.6 64-bit HotSpot JVM but obviously no guarantees of portability.
try {
Process p = Runtime.getRuntime().exec("sleep 10000");
Field pidField = p.getClass().getDeclaredField("pid");
pidField.setAccessible(true);
final int pid = pidField.getInt(p);
Process killProcess = Runtime.getRuntime().exec("kill -9 " + pid);
killProcess.waitFor();
System.out.println(p.exitValue());
} catch (Exception e) {
e.printStackTrace();
}
The Gnome System Monitor (linux version of Windows Task Manager) uses libgtop2 package. Documnetation here: http://library.gnome.org/devel/libgtop/stable/
Also you can check the source of System Monitor to see how it uses the libgtop2 functions.
Most of the information you require is available via the /proc filesystem, although you may require the correct permissionings to read everything there. Note that the contents of /proc are Unix-specific - e.g. different on Linux/Solaris, and I have no idea re. MacOSX.
If you want to kill a process you've spawned yourself, then Process.destroy() is worth looking at. Otherwise you're going to have to execute kill. To use this nicely you should send a SIGINT, and if that doesn't work, then send a SIGKILL (to forceably terminate - I'm not sure if Process.destroy() does this)

Categories

Resources