Solved

How to run a process?

Posted on 1998-05-27
7
210 Views
Last Modified: 2010-04-16
I have an interactive command prompt-based program which I can execute at the command prompt (I am running on NT) by either typing a program name and interacting with the program or by putting my responses into a text file and typing at the prompt "my_prog input_file".  The program runs reading the inputs and producing the outputs.

I am trying to run this program from within a Java application by using the code below:

import java.io.*;

public class OsUtil
{
    public OsUtil()
    {
    }

    public static void main(String[] args)
    {
        // Define a command
        String commandName = "clsqry";

        // Execute a command
        try
        {
            Process process = Runtime.getRuntime().exec(commandName);

            // Get the process input
            DataOutputStream processInput = new DataOutputStream(process.getOutputStream());

            // Create a file input stream to read the program input
            DataInputStream fileInput = new DataInputStream(new FileInputStream("input.txt"));

            // Start the process feeder thread
            ProcessFeeder feeder = new ProcessFeeder(fileInput, processInput);
            feeder.start();


            process.waitFor();
            System.out.println(process.exitValue());
            process.destroy();


            // Get the process output
            BufferedReader out = new BufferedReader(new InputStreamReader(process.getInputStream()));

            // Print the output
            String nextLine;
            while((nextLine = out.readLine()) != null)
            {
                System.out.println(nextLine);
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        catch(InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}

    // A separate thread to supply input to the process
    class ProcessFeeder extends Thread
    {
        DataInputStream fileInput;

        DataOutputStream processInput;

        ProcessFeeder(DataInputStream in, DataOutputStream out)
        {
            this.fileInput = in;
            this.processInput = out;
        }

        public void run()
        {
            // Read input from the file and send it to the process
            String nextLine;

            try
            {
                while((nextLine = fileInput.readLine()) != null)
                {
                    processInput.writeChars(nextLine);
                    System.out.println("Read input line: " + nextLine);
                }
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }
    }

File "input.txt" contains the user prompts.  When I run this program it simply hangs without doing anything.  I tried changing the command from simply "clsqry" to "clsqry < input.txt" (and commenting out the code which supplies input). I tried placing process.waitFor() call at the end of the program after the output has been read. Nothing helps.

So, what is the appropriate way to run an interactive command-line program on NT (I hope for a cross-platform solution but NT would be a good start)?
0
Comment
Question by:msmolyak
  • 4
  • 3
7 Comments
 
LVL 6

Accepted Solution

by:
gadio earned 100 total points
ID: 1221533
msmolyak, I think that what you are missing is a close of the processInput at the end of the reading. probably the buffer didn't flushed to the new process when the feeding thread finished reading the input file. I have added a close and tried it (on UNIX machine) and it worked. Try it on the NT and tell me if it helped. Heres what I changed:

----------------

    try
    {
       while((nextLine = fileInput.readLine()) != null)
       {
           processInput.writeBytes(nextLine+"\n");
           System.out.println("Read input line: " + nextLine);
       }
       processInput.close();  // ---****< line added >*****---
    }
    catch(IOException e)
        {
           e.printStackTrace();
        }
    }

0
 
LVL 5

Author Comment

by:msmolyak
ID: 1221534
I did close the process output stream (which accepts the input) as you suggested. Alas, it did not have any effect on the program. When I step throgh it it gets stuck on process.waitFor() call. Which tells me that it is sitting in memory waiting for inputs. Based on the printouts in the Thread class all the inputs were written and the stream closed.
0
 
LVL 6

Expert Comment

by:gadio
ID: 1221535
msmolyak, did you notice that I added at the end of each write a newline? It seems that without it the process got all the input as a single line. Also I changed the write from writeChars to writeBytes. writeChars didn't work when I tried it.
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 5

Author Comment

by:msmolyak
ID: 1221536
Sorry, I did not mention it. Yes, I put those lines in place of mine. I even added a call to flush() after each write. Same effect.
0
 
LVL 6

Expert Comment

by:gadio
ID: 1221537
I don't have an NT machine but I'll try it on win95, see how it goes.
0
 
LVL 5

Author Comment

by:msmolyak
ID: 1221538
You know what. I placed call to waitFor() after the code which reads the output and everything worked. Is waitFor() supposed to be called before or after you read the output?
0
 
LVL 6

Expert Comment

by:gadio
ID: 1221539
Oooh. That makes sense. This can also explain the fact that it worked on Unix and not on NT. Probably (I have to check this), the process on NT can't exit until it output buffers are cleared. On Unix I know that the process can exit at these conditions.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This video teaches viewers about errors in exception handling.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now