Invoking Java from C and capturing System.out

Hi,
I know very little about C but have a question related to invoking a Java process from C. Perhaps someone can help me.
I've been looking at the example at http://java.sun.com/docs/books/jni/html/invoke.html and seen how to invoke my Java program with:
(*env)->CallStaticVoidMethod(env, cls, mid, args);
in their example the Java program prints one line to System out with:
System.out.println("Hello World " + args[0]);
and says running the program produces:
Hello World from C!
What I want to know is, how in the C program can I capture the output the Java program sends to System.out, as I want to do something with the output other than have it print into the console.
Hope that makes sense.

I'm not totally clear on your question but I'll take a stab.
It seems to me like you are trying to get the output from a java program into a C program. If this is the case then there are many ways to do this - many of which are more simple that using JNI. However, if you absolutely must use JNI for this application then I suggest you take some more time to learn about C and JNI as I imagine this sort of thing is non-trivial and will required a level of understanding of C that you currently don't have. You may also want to cross-post onto the JNI forum.
If you can do this without using JNI then I'd suggest doing the standard fork/exec/pipe routine. This means, that in your C program you will call the functions fork (to create a new process that is subordinate to the currently running one), exec (in the subprocess which will replace the current program image in memory with that of another program you wish to execute, in this case, a JVM with a running application), and popen (which creates a "pipe" between the standard output of the Java program [System.out] and some input stream in the C program).
Finding an example of a program that does this fork/exec/pipe pattern on the web shouldn't be too hard. Hope this helps.
-mike

Similar Messages

  • How to capture System.out, done by another program

    Hi All,
    My application runs other application in back. How can I capture system.out.println() written by another application & display via dialog box.
    Like :execl() or execv() function in C runtime library. Where every printf() message printed to passed buffer.
    Thank you,
    Avin Patel

    You can create an InputStream from a started process. Then read all the bytes from the inputstream and write them to an outputstream (like System.out)
    Process p = Runtime.getRuntime().exec(COMMAND);
    InputStream is = p.getErrorStream();   //Or another stream
    int[] buffer = new int[128];
    while((read = is.read(buffer)) != -1){
    System.write.out(buffer, 0, read);
    }

  • Capturing System.out messages

    Hey all,
    Just wondering what the easiest way to capture System.out messages of a process, and store these messages in an Array, Vector, or a Buffer where I could read these messages line by line later?
    Basically one process System.out.println()'s information I need to use as a variable for a second process. Any help would be greatly appreciated.
    Thanks!

    Here is a class which redirects standard out and err to a JscrollPane.
    import java.io.*;
    import javax.swing.*;
    public class EOutputConsole extends JScrollPane {
      Object lock = new Object();
      final JTextArea text = new JTextArea(10,30);
      PrintStream consoleOut;
      public EOutputConsole() {
        setViewportView(text);
        setupOutput();
       * An extention of PrintStream that notifies a lock
       * as it's executing its write method. This tells
       * an output console that it has input ready.
      class ConsolePrintStream extends PrintStream {
        Object lock;
        public ConsolePrintStream(Object lock, OutputStream out) {
          super(out);
          this.lock = lock;
        public void write(byte[] buf,
                          int off,
                          int len) {
          synchronized(lock) {
            lock.notify();
            super.write(buf,off,len);
       * A class that extends PrintStream to throw away all
       * input sent to it. This is used to supress standard out
       * and speed up test model runs with debugging output
      class NullPrintStream extends PrintStream {
        public NullPrintStream(OutputStream out) {
          super(out);
        public void write(byte[] buf,
                          int off,
                          int len) {
      public void suppressStandardOut() {
        // create a dumby temp file to use as an output stream
        // nothing will ever actually be written to the file
        try {
          File dumbFile = File.createTempFile("notme", "not1337");
          dumbFile.deleteOnExit();
          PrintStream out = new NullPrintStream(new FileOutputStream(dumbFile));
          System.setOut( out );
          System.setErr( out );
        } catch(IOException ioe) {
          System.out.println("Error supressing standard out");
          ioe.printStackTrace();
      public void availableStandardOut() {
        System.setOut( consoleOut );
        System.setErr( consoleOut );
      private void setupOutput() {
        Thread printer = new Thread( new Runnable() {
            public void run() {
              PipedInputStream pipe = new PipedInputStream();
              BufferedReader in = new BufferedReader
                (new InputStreamReader( pipe ));
              try {
                PipedOutputStream pipeOut = new PipedOutputStream(pipe);
                consoleOut = new ConsolePrintStream(lock, pipeOut);
                System.setOut( consoleOut );
                System.setErr( consoleOut );
              catch (Exception e) {
                System.out.println("Failed to create Pipe for System.out");
                e.printStackTrace();
                return;
              try {
                for(;;) {
                  while(!in.ready()) {
                    synchronized(lock) {
                      lock.wait();
                  text.append(in.readLine()+"\n");
                  verticalScrollBar.setValue(verticalScrollBar.getMaximum());
              } catch (Exception e) {
                System.out.println(e);
                e.printStackTrace();
        printer.setDaemon(true);
        printer.start();
    }

  • How to bulk import data into CQ5 from MySQL and file system

    Is there an easy way to bulk import data into CQ5 from MySQL and file system?  Some of the files are ~50MB each (instrument files).  There are a total of ~1,500 records spread over about 5 tables.
    Thanks

    What problem are you having writing it to a file?
    You can't use FORALL to write the data out to a file, you can only loop through the entries in the collection 1 by 1 and write them out to the file like that.
    FORALL can only be used for SQL statements.

  • How to exclude specific PCs or Organization Unit from discovery and All system collection?

    We want to exclude some PCs from discovery and All System collection.
    1. We want to exclude with out modfing query of All System collection and without modifiing registry.
    2. We want to exclude with Organization unit container.
    We have also tested Include and exclude option which is avaible in system discovery (Discovery method)  but it is not working as per expected.
    Please help us.

    Jason messaged me offline and said that the method of denying read access does not always work. I was thinking that I had done that back in 2003 but have not tested it in the past 10 years or so. It would be easy to test though if you want to give it a try.
    Just browse to the OU on ADUC, right click, properties, security tab. Click Add, change the object type to computers, enter the same of the server that performs discovery, click ok, click deny on all boxes and click OK.
    Actually I just did it to write the instructions above. When I see in my adsysdis.log clearly indicates to me that, in my environment, this works.
    John Marcum | http://myitforum.com/myitforumwp/author/johnmarcum/

  • I purchased a book from itunes and cannot figure out how to get it on my ipod nano 7.  I cannot find an answer that works.

    I purchased an audio book from itunes and cannot figure out how to get it on my nano 7.  I have tried everything. 

    Have you double checked to make sure these Audiobooks are configured to sync to your iPod from under the iPod's Books configuration tab in iTunes?  This is assuming that the audiobooks are already stored in your iTunes library and appear under the Books category.
    To access this configuration tab, plug in your iPod and select it from under the Devices section in the left hand pane of iTunes to bring yourself to the iPod's Summary tab. Now locate the Books tab across the top in the main iTunes window and select it. Here you can configure what and how audiobooks are synced to the device.
    If you make any changes to this tab, make sure to hit the Apply button on in the lower right hand corner. This will sync the updated changes to your device.
    B-rock

  • Trying to publish to my BC from Muse and it times out.

    I've been tryng to publish a simple page to BC from muse and it times out, the manage BC under file is greyed out. 
    Don't know what else to do???

    Can we reopen this issue please.
    I've been getting the same message. Applied the above instructions but still get same messaging.
    Here are the screenshots  (NOTE - T & C for Trial Software)
    I've also deleted Muse from the computer and reloaded it through my Creative Cloud account.
    Thanks for your help.

  • Tomcat Java Servlets, how to log System.out.println() messages

    I have recently installed a new (x86) Mac OS Xserve, and am porting some Java application Servlets from an existing older Mac OSX server. All the servlets were working (I am connecting via port 9006). I have carefully used the old JDK 1.4 compiler, edited my server.xml (for port 9006) and web.xml files, etc. The Tomcat example servlets work fine, and all my (other) servlets work fine, with one exception, where I get the typically vague "java.io.IOException: Server returned HTTP response code: 500" message.
    Trouble is, I cannot get the Java System.out.prinln statements to go to the Tomcat/logs/ log files (they are all there and updating with Tomcat HttpServlet messages), in order to properly debug.
    Is there a server.xml value somewhere I can make the change?
    On another minor (possibly related) point, does anyone know what the path info ='null' means in the Tomcat access log? e.g.,
    StandardContext[/my_servlets]: Mapped to servlet 'myServlet' with servlet path '/myServlet' and path info 'null'
    It is the only other suspicious message I get in all the logs.
    One other point: my java application that fails uses threads. All the individual classes that use the threads work when run interactively, but as soon as I call them from final Serlet class that extends HttpServlet, I get a null pointer exception. Is there something unique about the Tomcat 4.1 threading that could be causing it?
    I want to avoid upgrading to Tomcat 5 at this point, if I can avoid it. My applications are modest in scope, and the last time I upgraded to Tomcat 5, it took me days to get it working properly, and I lost all access to it from the Server Admin application.

    I have found a solution: Via the Tomcat Admin web page I set the Context field "Swallow Output" to "true".

  • Invoking Java from C on Solaris

    Hi!
    I know, similar questions concerning this issue have been posted here before, but none of the answers helped me out.
    I'm using Java 1.3 and cc (SC4.0 18 Oct 1995 C 4.0) on Solaris 2.6
    I'm trying to compile and run the exact example from sun's web page to invoke a JVM from C. The code can be found here:(http://java.sun.com/docs/books/tutorial/native1.1/invoking/invo.html).
    this is the make-command:
    cc -I/jdk/1.3/include -I/jdk/1.3/include/solaris -L /jdk/1.3/jre/lib/sparc -L
    /jdk/1.3/jre/lib -o invoke -ljava -ljvm -lthread -lc invoke.c
    I can't avoid getting the follwing warnings:
    "invoke.c", line 39: warning: argument #2 is incompatible with prototype:
    prototype: pointer to pointer to void :
    "/app/unido-inf/sun4_56/jdk/1.3/include/jni.h", line 1911
    argument : pointer to pointer to pointer to const struct
    JNINativeInterface_ {pointer to void reserved0, pointer to void reserved1,
    poi...
    and the compiled program crashes with a core dump (a very helpful error message!)
    ./invoke
    Segmentation Fault (core dumped)
    [status 139]
    Has anyone ever managed to run this example program from Sun's site?
    Is it the C-Compiler that matters here?
    Any help would be greatly appreciated!!
    Patrick.

    This should be a version problem. JNI itself has versions like JDK, as the example is for JDK1.1, and JNI has been updated in JDK1.3 (I can't remember the version number, but they are different). And the invocation API and implementation has changed. So when you run the program, it ends up with incompitable data type and/or method signiture/prototype. Maybe you should try to use JDK1.1 or find a decent tutorial about JDK1.3's invoke API.

  • Officejet Pro 8600 e. Problem scanning from Scan and Capture App in Win 8.1

    Officejet Pro 8600 e.  New.
    Installed on HP Envy 23 Touch. Running Windows 8.1.  
    Wireless set up. Prints fine.  Problem is scanning from the HP Scan and Capture Software App in Win 8.1  
    Using Scan and Capture App I can scan photos fine.  They come out clear.  Scanning documents in GRAY has multiple bands/lines in gray over the entire page running vertically.  Scanning documents in COLOR are fine.
    Also, if I scan from the printer directly using the touch screen on the printer, the scan output is fine.
     I did the Scan utilty to discover any errors and it did not show any.  I think it's a software error.  I am going to uninstall the HP Scan App and then reinstall.  So, I will do the uninstall/reinstall and report back.
    Also, I would like to know if there is a desktop program for scanning?  I would prefer to use that instead of the Modern HP Scan and Capture App.
    Thanks....
    This question was solved.
    View Solution.

    Hi artrum,
    I understand you've been experiencing issues scanning from your Officejet 8600 using the Windows Scan and Capture program. I will certainly do my best to help you with this!
    From what you've explained, I believe you're correct, it does seem like it's an issue just with the Windows Scan and Capture program and as you've been able to scan from the front panel of the printer you definitely have the HP software installed. What I'd like to do is have you use the HP Scan software, where you should no longer run into issues.
    To access the HP Scan software and be able to access it easily from your desktop I'd like you to follow the steps below:
    1. Go to your start screen and just start typing File Explorer. You should be able to then open it to access your computer's files.
    2. Then open Local Disk (C: ), followed by Program Files (x86), followed by HP, then HP Officejet Pro 8600, followed finally by bin.
    3. In the bin folder you should see HPScan. You will want to right click on HPScan and go to Send To and then select Desktop.
    Now you should see HP Scan on your desktop and be able to open it and scan through that application.
    Hope this helps, have a great day!
    Please click “Accept as Solution ” if you feel my post resolved your issue, as it will help others find the solution faster
    Click the “Kudos Thumbs Up" on the right to say “Thanks” for helping!
    **MissTeriLynn**
    I work on behalf of HP

  • Return Vector from function and print it out.

    Hey guys, I am not sure I'm doing this right. I have a class that currently has one function "getVector". This takes a string that is input and turns into a Vector array and returns the array as Vector.
    Then in the second class I simply want to print out the Vector. I get no errors, but it doesn't print anything.
    If anyone can see what I am doing wrong I'd appreciate the help.
    Thanks!
    Here is the first class that has the getVector function
    import java.util.*;
    public class GetArrays {
        public Vector getVector (String s){
            Vector theVector = new Vector();
            StringTokenizer token=new StringTokenizer(s," ");
                while (token.hasMoreTokens()){
                    String tk=token.nextToken();// get each token
                    theVector.add(tk);
                 }// end while
            return theVector;
        }//end getVector
    }//end classAnd here is the class with main that tries to print it out.
    import java.util.*;
    public class ShowArrays {
        public static void main(String[] args) {
            ShowArrays showArrays = new ShowArrays();
            Vector theArray = new Vector();
            GetArrays getArrays = new GetArrays();
            theArray = getArrays.getVector("testing this function");
            ListIterator iterator = theArray.listIterator(theArray.size());
            while(iterator.hasNext()){
                System.out.println(iterator.next()+"\n");
              }// end while
        }//end main
    }//end class

    Remove the parameter to your call to. Adding this parameter starts the iterator at the element theArray.size(), which is the end of the array.
    ListIterator iterator = theArray.listIterator();

  • Java - Eclipse debug applet with System.out.print in jboss console

    I use System.out.print to debug my java programs using Eclipse. I'm new
    with applets, and when nothing showed up in the applet window, I tried
    using print statements. I was expecting to see them in the jboss console like
    always, but there was nothing there. I tried looking this problem up
    online and found nothing. Does anyone know how I can use print
    statements to debug my applet? (Japplet to be specific).

    System.out.println works for me. The output statment are visible in the Console Window within Eclipse.

  • Invoking Forms from JSP and Vice versa

    Hi,
    I am in to a requirement like invoking a screen developed using Oracle Forms 6i from JSP and vice versa.
    1. Could you please anybody help to get the documents to be refered to get more idea on this?
    2. Is it possible only by Oracle ADF?
    Please help me on this.
    Thanks & Regards
    M Thiyagarajan

    Hi All,
    Thanks a lot for the clarifications.
    Actually, integration should happen between forms and JSP. Parameters need to be passed to and forth. I will go through the specified link.
    Also could you please clarify me where exactly, ADF comes into picture? or what are all the advantages when we go for ADF?
    Thanks & Regards
    M Thiyagarajan

  • Upgraded to ML from L and am locked out, will not accept password

    just upgraded to ML form L and am locked out, won't accept my password....i cant use my laptop now, what can i do?

    I haven't tried this process in ML but I don't think it's changed from L.
    http://osxdaily.com/2011/08/24/reset-mac-os-x-10-7-lion-password/

  • JDBC Lookup in PI 7.1 - SELECT ? FROM DUAL and Connection timed out

    Hi,
    We have a scenarios (Idoc to JMS) with JDBC lookup. We have used graphical JDBC lookup functionality.
    We are reading country names for a given country code from SAP in an external database table. The query is so simple. That  should not take much time
    Now the actual issues is,
    When we are executing the scenario, its taking quite a long time. Almost 6 minutes to excute a mapping. Which causing high performance issue in the Porduction.
    We started the inviestigation about found some interesting stuff. Here we have used Willy Introscope for the investigation.
    1. First few messages are taking quite a long time. LIke 6 minutes per messages. As i can see in the log i am getting below error in Willy,
    I dont know why PI is executing below queury apart from real secelt query to fetch the country name. I am getting below error: Error Message: Backends|ABCD2 mydatabase01-1526 (Oracle DB)|SQL|Dynamic|Query|SELECT ? FROM DUAL: java.sql.SQLException: Io exception: Connection timed out
    2. After couple of messages, interface works very normal. I mean rest of the messages works pretty fine.
    Please let me know if you have any idea about this error. What could be the problem for the issue.
    Thank you in advnace.
    Best Regards,
    Prasad.

    Did you check how many SQL requests were executed per one message ? Do you have a log of these SQL requests ?
    I assume that the country table is quite small, so that lookup should not be an issue.
    About this:
    >Message: Backends|ABCD2 mydatabase01-1526 (Oracle DB)|SQL|Dynamic|Query|SELECT ? FROM DUAL: >java.sql.SQLException: Io exception: Connection timed out
    1. I only know SELECT * FROM DUAL, not SELECT ? FROM DUAL. Better use the former
    2. the exception means that the database server can not be reached => check your network configuration
    So I assume that there is a network (performance) problem between PI and this Oracle server. Or the Oracle Server is so overloaded that it has (sometimes) problems in processing new requests.
    CSY
    Edited by: Christian Sy on Mar 9, 2010 10:17 AM

Maybe you are looking for

  • Publishing to a website

    can anyone advise me on publishing to my website? I am new to the whole process?

  • Do I have to configure DNS server before configuring VPN server?

    Hi, In my journey to get this mac os X server to actually work... Do I need to configure DNS server on Mac OS X server first before setting up VPN or ICHAT server? Or, it seems that I can use my D-Link Gaming router as a DNS server. I think I'm most

  • Problem While installing ODI 11g

    Hi, I have downloaded the latest version of ODI and tried to install but I am getting the following error. http://2.bp.blogspot.com/-oOb6cVeQq5c/US2ly0p2-pI/AAAAAAAAAeI/3SA8zdP0CO0/s1600/odierror.JPG I tried three time but faced the same error. I am

  • Edit imported music on a video clip

    In iMovie '06 I could mute or lower the volume of imported music when I want to hear the imported video clip sound to be heard instead of the imported music. Afte the video clip the music could be un-muted. How can this be done in iMovie '08?

  • Can I find out how many people are subscribed to my RSS feed?

    Just curious - I don't want to know who they are, or spam them - I'm just wondering about a count. --drkenfp