Jump to content

Invoking C

75% developed
From Wikibooks, open books for an open world

Navigate Advanced topic: v  d  e )


You can use Runtime.exec() method to invoke a program from within a running Java application. Runtime.exec() also allows you to perform operations related to the program, such as control the program's standard input and output, wait until it completes execution, and get its exit status.

Here's a simple C application that illustrates these features. This C program will be called from Java:

#include <stdio.h>

int main() {
    printf("testing\n");
    return 0;
}

This application writes a string "testing" to standard output, and then terminates with an exit status of 0. To execute this simple program within a Java application, compile the C application:

Computer code Compilation
$ cc test.c -o test

Then invoke the C program using this Java code:

Computer code Code listing 10.2: Invoking C programs.
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.InterruptedException;
import java.io.Process;
import java.io.Runtime;

import java.util.ArrayList;

public class ExecDemo {
    public static String[] runCommand(String cmd) throws IOException {
        // --- set up list to capture command output lines ---
        ArrayList list = new ArrayList();

        // --- start command running
        Process proc = Runtime.getRuntime().exec(cmd);

        // --- get command's output stream and
        // put a buffered reader input stream on it ---
        InputStream istr = proc.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(istr));

        // --- read output lines from command
        String str;
        while ((str = br.readLine()) != null) {
            list.add(str);
        }

        // wait for command to terminate
        try {
            proc.waitFor();
        }
        catch (InterruptedException e) {
            System.err.println("process was interrupted");
        }

        // check its exit value
        if (proc.exitValue() != 0) {
            System.err.println("exit value was non-zero");
        }

        // close stream
        br.close();

        // return list of strings to caller
        return (String[])list.toArray(new String[0]);
    }

    public static void main(String args[]) throws IOException {
        try {

            // run a command
            String outlist[] = runCommand("test");

            // display its output
            for (int i = 0; i < outlist.length; i++)
                System.out.println(outlist[i]);
        }
        catch (IOException e) {
            System.err.println(e);
        }
    }
}

The demo calls a method runCommand to actually run the program.

Example Code section 10.1: Running a command.
String outlist[] = runCommand("test");

This method hooks an input stream to the program's output stream, so that it can read the program's output, and save it into a list of strings.

Example Code section 10.2: Reading the program's output.
InputStream istr = proc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(istr));
             
String str;
while ((str = br.readLine()) != null) {
    list.add(str);
}

Migrating C to Java

[edit | edit source]

Tools exist to aid the migration of existing projects from C to Java. In general, automated translator tools fall into one of two distinct kinds:

  • One kind converts C code to Java byte code. It is basically a compiler that creates byte code. It has the same steps as any other C compiler. See also C to Java JVM compilers.
  • The other kind translates C code to Java source code. This type is more complicated and uses various syntax rules to create readable Java source code. This option is best for those who want to move their C code to Java and stay in Java.


Clipboard

To do:
Add some examples.