sanjitmohanty

December 20, 2011

Overcoming Runtime.exec havoc with JNA

Filed under: Java — Sanjit ... @ 8:14 am

Issue: 

Think of a situation where your java application wants to change the owner & permission of a unix file programmatically. With JRE1.5, the obvious way to achieve this could be the usage of Runtime.exec.  With Unix as runtime, this invokes fork() which makes a complete copy of entire parent process’s address space and exec() then turns that copy to a new process. The disadvantage of this approach is that you will end up with Out Of Memory issues without a good reason.

Solution:

Use Java Native Access to invoke native C POSSIX library!

JNA allows you to call directly into native functions using natural Java method invocation. The Java call looks just like it does in native code. The JNA library uses a small native library stub to dynamically invoke native code. The developer uses a Java interface to describe functions and structures in the target native library. This makes it quite easy to take advantage of native platform features without incurring the high overhead of configuring and building JNI code for multiple platforms.

Below is a java code snippet which changes owner and permission of a unix file without using Runtime.exec. You need to place jna.jar and platform.jar in your classpath for compiling and running this application :-


import com.sun.jna.Library;
import com.sun.jna.Native;

public class FilePermOwnerChange {
public interface POSIX extends Library {
public int chmod(String filename, int mode);
public int chown(String filename, int userId, int groupId);
}

  public static void main(String[] args) {
       POSIX posix = (POSIX) Native.loadLibrary("c", POSIX.class);
       posix.chmod("/tmp/BufCre.txt", 0664); //0664 is just an example
       posix.chown("/tmp/BufCre.txt", 1000, 1000); // 1000 is just an example. Give the UID and GID respectively for the new owner of this file.
  }
}

About these ads

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Rubric Theme. Create a free website or blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: