2

I am new to JAVA Programming & JNI. How to call getpid() C library function in Java program using JNI? I went through following post How can a Java program get its own process ID? but unable to run program. Thanks in advance

I have written following program

public class ProcessId  
 {  
    public static void main(String[] args) {  
            CLibrary clib = (CLibrary) Native.loadLibrary("c",Library.class);    
            clib.getpid();  
            System.out.println("Process Id is "+getpid());  
        }  
} 

I am getting following errors

1)Library cannot be resolved to a type
3)The method getpid() is undefined for the type ProcessId

Above mentioned post talk about platform.jar file. I downloaded one from http://grepcode.com/snapshot/repo1.maven.org/maven2/net.java.dev.jna/platform/3.4.0 and included in Project Libraries. But it still not worked out..

Community
  • 1
  • 1
user2201980
  • 367
  • 2
  • 4
  • 14
  • There's hundreds of examples of JNI available here and elsewhere on the net, and `getpid` isn't exactly the most complexe C API ever. Show exactly what you tried and explain exactly what doesn't work/how it fails/what errors you're getting. – Mat Aug 10 '13 at 10:19
  • 1
    As Mat says, you don't remotely say what you tried/ or provide the slightest detail of what doesn't work/ how it went wrong & error messages. Exact detail is required.. this is just a ridiculously lazy question. – Thomas W Aug 10 '13 at 10:27
  • if you just want the process ID but don't insist on JNI to get it, there are some solutions here that might be faster to implement : http://stackoverflow.com/questions/35842/how-can-a-java-program-get-its-own-process-id – Graham Griffiths Aug 10 '13 at 11:40

1 Answers1

2

Mat & Thomas ,Thanks for your help.. I managed to call C library function from Java.. Following steps I took.
Step 1) Downloaded jna.jar from the GitHub. https://github.com/twall/jna
Step 2) Added above jar file in Project Libraries
Step 3) Written following code

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

/** Simple example of native library declaration and usage. */
public class ProcessId {  
    public interface CLibrary extends Library {    
        CLibrary INSTANCE = (CLibrary) Native.loadLibrary(  
            (Platform.isWindows() ? "msvcrt" : "c"), CLibrary.class);  
        void printf(String format, Object... args);  
        int getpid();  
    }  

    public static void main(String[] args) {  
        CLibrary.INSTANCE.printf("Hello, World\n");  

        System.out.println("My Process id is "+ CLibrary.INSTANCE.getpid());  

        for (int i = 0; i < args.length; i++) {  
            CLibrary.INSTANCE.printf("Argument %d: %s\n", i, args[i]);  
        }  
    }  
}  

Its working!!!

user2201980
  • 367
  • 2
  • 4
  • 14