Calling a C Program

I’ve created a console C program that has parameters input on thecommand line and would like to create a Java application that selectsthe parameters and calls the C program from Java.

The Runtime class allows you to execute system commands from a Javaprogram. Just fetch the application Runtime with Runtime.getRuntime()and then call the appropriate exec() method.

There are fourvariations of the exec() method. You can either pass a command as asingle string that will be parsed by the exec() method into commandand arguments, or you can explicitly define which strings are part ofthe command and which are arguments in a string array.

You can alsodefine the values of environment variables with a string array. Theexec() method will return a Process reference which can be used tointeract with the executed command. You can wait for the process tofinish with waitFor() or interact with any one of its standard input,output, or error with any one of getInputSteram(), getOutputStream, orgetErrorStream(). The following example executes a Unix grep commandand copies its output to standard output.

import*;public class ExecExample {  public static void main(String[] args) {    Process process;    Runtime runtime;    String[] command = { "/bin/grep", "ExecExample", "" };    InputStream input;    int bytes;    byte[] buffer;    runtime = Runtime.getRuntime();    try {      process = runtime.exec(command);      // Copy process output to our standard output      buffer = new byte[1024];      input = process.getInputStream();      while((bytes = > 0)	System.out.write(buffer, 0, bytes);    } catch(IOException e) {      e.printStackTrace();      return;    }  }}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS