UNIX pipe and Java

Hello everybody,
I'm trying to write a program that executes a perl script...
Process p = Runtime.getRuntime().exec("echo [email protected] | /root/bin/bulkmakemail");
it does not work
apparently exec() method does not know how to deal with UNIX pipe
or maybe it does but I don't uderstand how to make it work
can anybody help me?
thanks in advance
Roman

How about:
Process p = Runtime.getRuntime().exec(
"sh -c 'echo [email protected] |
| /root/bin/bulkmakemail'"
);Bingo. And to make this even more quote-mangling-proof, do this:
String[] args = new String[] {
"/bin/sh",
"-c",
"echo [email protected] | /root/bin/bulkmakemail"
... Runtime.getRuntime().exec(args);
This will prevent any problems with all those nested quotes getting mangled during the parse of the command line by the java runtime.
(Runtime.exec(String) has to be parsed by the java runtime itself so as to build the Unix exec() argv list - best to help it along yourself by calling Runtime.exec(String[]) instead).

Similar Messages

  • Unix pipe and java program

    Hi,
    I want to make an utility that reads from a Unix pipe and prodouce an output to the screen. i.e. there is a "input.log" file to be processed as:
    # tail -f input.log | java myprog | console
    this time, "myprog" should take last few lines from "input.log" and process it in some way and prints the result to the shell.
    Please suggest me possible solution.
    Sumit

    if you want to create your java program in such way that it could take input from pipe and produce output to pipe, then you actually have to get input ftom System.in and produce output to System.out
    but what you mean by that | console after java myprog, that i don't understand...
    actually, what you decribe to be your problem, could be solved with cat or furthermore, it could be solved with not touching anything...
    since when you pipe progs together, then first progs output would be connected to seconds' input and so forth...
    maybe this helps a bit...

  • Unix Named pipes from Java

    Hello,
    My problem is with a unix named pipe which I have to write to. To do it, I have to use a FileOutputStream. It works fine when some process is reading the named pipe. My problem is when there is no process reading the pipe, my Java app gets blocked in the open method of the FileOutputStream.
    What we want is to open the FileOutputStream without blocking, although there is no process reading the pipe.Is it possible from Java? Is there anything similar to the unix NON_BLOCK?
    Thank you in advance.
    RCG@

    Hi,
    I think, in UNIX you would get the same problem, at least if you are writing then.
    By NON_BLOCK you would not be blocked, but you would get an error each time you try to write. So in UNIX in most cases the blocking is quite adequate: you want to "listen", until someone "calls", and then continue.
    I assume you want to open the pipe first to see if you can access it successfully.
    For this, try the same trick like with C in UNIX:
    Open that pipe first for reading. So there is a reading process: your JVM.
    Does this help you?
    Regards,
    Hartmut

  • Newbie: how to handle pipes and semicolons while launching UNIX commands?

    Good afternoon,
    I am trying to write a Java class that can launch UNIX commands.
    Launching simple commands (date, ps -ef) works fine, but when I start using pipes and semicolons, it goes wrong:
    Java code (pipe example):
            String command = "ps -ef | grep config";
            Process child = Runtime.getRuntime().exec(command);Result:
    usage: ps [ -aAdeflcjLPy ] [ -o format ] [ -t termlist ]
            [ -u userlist ] [ -U userlist ] [ -G grouplist ]
            [ -p proclist ] [ -g pgrplist ] [ -s sidlist ]
      'format' is one or more of:
            user ruser group rgroup uid ruid gid rgid pid ppid pgid sid taskid
            pri opri pcpu pmem vsz rss osz nice class time etime stime
            f s c lwp nlwp psr tty addr wchan fname comm args projid projectJava code (semicolon example):
            String command = "date;ps -ef";
            Process child = Runtime.getRuntime().exec(command);Result:
    date;ps: not foundClearly the pipes and the semicolons are handled by the UNIX shell and cannot be put in the Java source code as such.
    Does anybody know a way around this?
    Thanks
    Dominique

    Pipes and semicolons are interpreted by a shell (bash, csh etc) and when one executes as you are doing no shell is involved. This is easy to solve by using the alternate version of exec() which takes an array as an argument and to use your shell of choice. For example :-
    String[] command = {"bash", "-c", "date;ps -ef"};Note that the third argument is the whole of the command to be interpreted.
    Two points to consider. First you should read, digest and implement all the recommendations in http://www.javaworld.com/jw-12-2000/jw-1229-traps.html; failure to do so will at some point lead to significant loss of hair. Second you should probably use ProcessBuilder rather than Runtime.exec(). Behind the scenes Runtime.exec() uses ProcessBuilder but ProcessBuilder provides a better interface with more features.

  • Using utl_file and unix pipes

    Hi,
    I'm trying to use utl_file and unix pipes to communicate with a unix process.
    Basically I want the unix process to read off one pipe and give me back the result on a different pipe.
    In the example below the unix process is a dummy one just copying the input to the output.
    I cant get this to work for a single plsql block writing and reading to/from the pipes - it hangs on the first read of the return pipe.
    Any ideas?
    ======== TEST CASE 1 ===============
    create directory tmp as '/tmp';
    on unix:
    cd /tmp
    mknod outpip p
    mknod inpip p
    cat < inpip > outpip
    drop table res;
    create table res (m varchar2(200));
    declare
    l_filehandle_rec UTL_FILE.file_type;
    l_filehandle_send UTL_FILE.file_type;
    l_char VARCHAR2(200);
    begin
    insert into res values ('starting');commit;
    l_filehandle_send := UTL_FILE.fopen ('TMP', 'inpip', 'A', 32000);
    insert into res values ('opened inpip ');commit;
    l_filehandle_rec := UTL_FILE.fopen ('TMP', 'outpip', 'R', 32000);
    insert into res values ('opened outpip ');commit;
    FOR i in 1..10 LOOP
    utl_file.put_line(l_filehandle_send,'line '||i);
    insert into res values ('written line '||i); commit;
    utl_file.get_line(l_filehandle_rec,l_char);
    insert into res values ('Read '||l_char);commit;
    END LOOP;
    utl_file.fclose(l_filehandle_send);
    utl_file.fclose(l_filehandle_rec);
    END;
    in a different sql session:
    select * from res:
    starting
    opened inpip
    opened outpip
    written line 1
    ============ TEST CASE 2 =================
    However If I use 2 different sql session (not what I want to do...), it works fine:
    1. unix start cat < inpip > outpip
    2. SQL session 1:
    set serveroutput on size 100000
    declare
    l_filehandle UTL_FILE.file_type;
    l_char VARCHAR2(200);
    begin
    l_filehandle := UTL_FILE.fopen ('TMP', 'outpip', 'R', 32000);
    FOR i in 1..10 LOOP
    utl_file.get_line(l_filehandle,l_char);
    dbms_output.put_line('Read '||l_char);
    END LOOP;
    utl_file.fclose(l_filehandle);
    END;
    3. SQL session 2:
    set serveroutput on size 100000
    declare
    l_filehandle UTL_FILE.file_type;
    begin
    l_filehandle := UTL_FILE.fopen ('TMP', 'inpip', 'A', 32000);
    FOR i in 1..10 LOOP
    utl_file.put_line(l_filehandle,'line '||i);
    --utl_lock.sleep(1);
    dbms_output.put_line('written line '||i);
    END LOOP;
    utl_file.fclose(l_filehandle);
    END;
    /

    > it hangs on the first read of the return pipe.
    Correct.
    A pipe is serialised I/O device. One process writes to the pipe. The write is blocked until a read (from another process or thread) is made on that pipe. Only when there is a reader for that data, the writer is unblocked and the actual write I/O occurs.
    The reverse is also true. A read on the pipe is blocked until another process/thread writes data into the pipe.
    Why? A pipe is a memory structure - not a file system file. If the write was not blocked the writer process can writes GBs of data into the pipe before a reader process starts to read that data. This will drastically knock memory consumption and performance.
    Thus the purpose of a pipe is to serve as a serialised blocking mechanism between a reader and a writer - allowing one to write data that is read by the other. With minimal memory overheads as the read must be serviced by a write and a write serviced by a read.
    If you're looking for something different, then you can open a standard file in share mode and write and read from it using two different file handles within the same process. However, the file will obviously have a file system footprint ito space (growing until the writer stops and the reader terminates and trashes the file) .
    OTOH a pipe's footprint is minimal.

  • Unix and Java

    Hey guys, im taking a computer programing class this semester and i was wondering if anyone has tried running Unix and Java OS on their macs? Im going to be writing my own programs for the class, such as creating a ball in a window and making it bounce etc. So far i been using my school computers and i was wondering how macs are?

    You can't run OS X without running Unix Strictly speaking, 10.4 (Tiger) isn't a certified Unix, so you may find a couple of non-standard things, but 10.5 (Leopard) will be certified.
    There are a ton of Java developers who work on Macs, so it's as good a platform as any for Java development. Apple are always a bit behind the official JDK releases because they produce their own rather than using Sun's, though. As for development tools, Apple's Xcode, Sun's Netbeans and IBM's Eclipse all work just fine on Macs-- although to be honest you shouldn't need much more than a decent text editor if you're just taking an elementary programming class.

  • Sco unix and java

    not sure if this is the right place to ask this question.
    1. Does sco unix support Java 5.0?
    2. What version of sco unix is capatible with Java 5.0 and Java 1.4.2?
    Thanks in advance!

    According to this you can install and execute J2SE for Intel Linux on S.C.O.

  • Problem with JSP and Java Servlet Web Application....

    Hi every body....
    I av developed a web based application with java (jsp and Java Servlets)....
    that was working fine on Lane and Local Host....
    But when i upload on internet with unix package my servlets and Java Beans are not working .....
    also not access database which i developed on My Sql....
    M using cpanel support on web server
    Plz gave me solution...
    Thanx looking forward Adnan

    You need to elaborate "not working" in developer's perspective instead of in user's perspective.

  • How can i use Unix database in java?

    How can i use Unix database in Java?
    Message was edited by:
    JPro

    I have not a clue about FoxPro, but the db then is FoxPro and not Unix. The better question would be "How do I connect to FoxPro DB running on Unix with JDBC?".
    My answer to that would be, search the Internet for a JDBC driver.

  • Running UNIX command from Java

    import java.lang.* ;
    import java.io.*   ;
    public class TestRunTime
        public static void main(String args[])
            int rc = -1 ;
            String yard = "psnsy" ;
            String ifwList = "[email protected],[email protected]" ;
            String cmd = "/usr/bin/mailx -r oracle -s \"PMC - Missing Interface Files from " + yard +
                               "\" " + ifwList + " < /interface/nwps/missingfiles.txt" ;
            rc = RunThis(cmd) ;
            System.out.println(rc) ;
        private static int RunThis(String str)
             Runtime rt = Runtime.getRuntime();
             int        rc = -1;
             try
                Process p = rt.exec(str);
                p.waitFor() ;
                BufferedReader buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line = "";
                while ((line = buf.readLine()) != null)
                   System.out.println(line) ;
                rc = 0 ;
                return rc ;
             catch ( Throwable t  )
                  t.printStackTrace();
                  rc = -1 ;
                  throw new RuntimeException() ;
    }When I run java TestRunTime
    all it does is hangs and never completes.
    I can run the string cmd from the UNIX shell and it runs as expected - I receive an email.

    jschell wrote:
    sabre150 wrote:
    Whether the detail is as you say or as I say does not remove the need to process the exec()ed processes stdout and stderr each in their own thread. Since the OP is not writing to stdin he can handle one of stdout or stderr in the Thread that invokes the exec() but the other needs a separate thread.If the streams are stripped from the process then...
    1. They should not be stripped until they are in their own thread.
    2. Each requires their own thread.
    But since the OP isn't stripping either, no other threads are needed. Nor does the OP need to strip them.I have to disagree. The following code is based on the traps article and sends output to stdout and to stderr from the 'sh' program. Run as is it deadlocks. Run by changing the 'false' to 'true' in the 'if' statement it does not deadlock.
    If one changes the code to process only stdout or stderr but not both then it deadlocks.
    Running the same code on Windows XP and Windows 2000 but using 'cmd.exe' instead of 'sh' and using 'dir' instead of 'ls' produces the same result.
    Running similar code that just runs a perl script without any stdin but that writes to both stdout and stderr it deadlocks if one does not process both stdout and stderr in separate threads.
    If one processes the Process stdout and stderr streams then one does not get a deadlock.
    This is entirely consistent with what the 'traps' article says and I hope consistent with what I have written in this thread.
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    class StreamGobbler extends Thread
        private int count = 0;
        private final InputStream is;
        private final String type;
        StreamGobbler(InputStream is, String type)
            this.is = is;
            this.type = type;
        public void run()
            try
                final InputStreamReader isr = new InputStreamReader(is);
                final BufferedReader br = new BufferedReader(isr);
                String line = null;
                while ((line = br.readLine()) != null)
                    System.out.println(++count + "\t " + type + "> " + line);
            } catch (IOException ioe)
                ioe.printStackTrace();
    public class Sabre20091015_2
        public static void main(String args[]) throws Exception
            final Process proc = Runtime.getRuntime().exec("sh");
            if (false)
                new StreamGobbler(proc.getErrorStream(), "ERROR").start();
                new StreamGobbler(proc.getInputStream(), "OUTPUT").start();
            final Writer writer = new OutputStreamWriter(proc.getOutputStream());
            for (int commandIndex = 0; commandIndex < 20000; commandIndex++)
                writer.write("echo Index " + commandIndex + "\n");
                writer.write("ls\n");
                writer.flush();
                writer.write("fnaskfdkdhflakjfljd\n");
                writer.flush();
            writer.close();
            final int exitValue = proc.waitFor();
            System.out.println("Exit value = " + exitValue);
    }

  • Will JCO work in Unix Environment and in Webshere 3.5

    I need to know whether SAPJCO.jar will work fine in unix environment and also whether is it compactible with websphere version 3.4.

    Hi Nikki,
    The answer for your question is <b>YES</b>. Unix supports java and Websphere. I think you are aware of of running complex J2EE applications on websphere. If you are able to run java based applications on your server and do not worry you can run sapjco.jar without any problem. Recently we had an integration project [ SAP R/3 and Lotus Domino Server]. It worked out perfectly.
    Read this will let you know more,
    http://www-128.ibm.com/developerworks/websphere/zones/portal/catalog/doc/appportletbuilder/ApplicationPortletBuilder_v410_wsdd.html
    Hope this will solve your problem.
    Thanks
    Kathirvel

  • VIs for using UNIX pipes?

    We're going to start working on an application that will eventually run on
    a UNIX machine, but in the meantime we'll develop on NT, which is what we're
    familiar with. One requirement is to communicate with another process through
    a UNIX pipe. Are there VIs built into the UNIX versions of LabVIEW for this?
    Or do we just use file I/O VIs? Or is there some other way to accomplish
    this?
    If there are VIs built in, where is the documentation? I checked the LabVIEW
    manuals, but I didn't find anything.
    Russell Davoli

    Russell Davoli wrote:
    > We're going to start working on an application that will eventually run on
    > a UNIX machine, but in the meantime we'll develop on NT, which is what we're
    > familiar with. One requirement is to communicate with another process through
    > a UNIX pipe. Are there VIs built into the UNIX versions of LabVIEW for this?
    > Or do we just use file I/O VIs? Or is there some other way to accomplish
    > this?
    >
    > If there are VIs built in, where is the documentation? I checked the LabVIEW
    > manuals, but I didn't find anything.
    >
    > Russell Davoli
    Yes there are VIs for named pipes in UNIX, Open, Close, Read, and Write
    They are under the communication palette. Check the online manual in the comm
    section.
    Kevin (my email is down)

  • Unix scripting in java

    hello
    im new to java.
    and i need to learn unix scripting in java. is it difficult to learn? can one learn it within a short span of time?! could anyone please give me some links where i can learn.
    tks

    I run UNIX systems, what do you mean by Java scripting?
    do you mean SH, BASH, TCSH, CSH shells and stuff? cause Java is platform independant?
    btw, are you using Linux or FreeBSD?
    p.s. Go FreeBSD!!

  • Call an interactive UNIX command from java

    Hi,
    I want to call a UNIX command from java. When issue the command 'htpasswd -c filename username' on UNIX terminal, it asks for the new password and the then confirmation password again (yeah, unfortunately the htpasswd installed on our system does not allow you proivde the password on the command line. So have to work interactively ). Now, I have written a simple java program RunCommand.java. I am hardcoding the password for the htpasswd command in the file (in the real situation, password will be generated dynamically). I want to issue 'java RunCommand' on the UNIX command line and get back the command prompt without being asked for the password twice. The code is below, but the Outputstream does not work as expected. It always asks for inputs. Any idea? Many thanks.
    import java.io.*;
    public class RunCommand {
    public static void main(String args[]) throws Exception {
    String s = null;
    try {
    String cmd = "htpasswd -c filename username ";
    // run a Unix command
    Process p = Runtime.getRuntime().exec(cmd);
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    OutputStream stdOut = p.getOutputStream();
    String pswd = "mypassword";
    while ((s = stdInput.readLine()) != null) {
         s = stdInput.readLine();
         stdOut.write(pswd.getBytes());          
         stdOut.flush();
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null) {
    System.out.println(s);
    stdOut.close();
    stdInput.close();
    stdError.close();
    System.exit(0);
    catch (IOException e) {
    System.out.println("exceptions caught: ");
    e.printStackTrace();
    System.exit(-1);

    There are only about 9 billion responses a day on how to do this. Use the search feature.

  • Execute unix command using java

    Hello
    Can we execute a unix command using java? If it is how we can execute. Is this affect the performance of the program.
    Thanks

    I tried what you said. But its not working and returning error message,
    java.io.IOException: CreateProcess: ls -a error=2
         at java.lang.ProcessImpl.create(Native Method)
         at java.lang.ProcessImpl.<init>(Unknown Source)
         at java.lang.ProcessImpl.start(Unknown Source)
         at java.lang.ProcessBuilder.start(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
    If i try this statement,
    Runtime.getRuntime().exec("c\windows\notepad");
    It is working fine.
    Any idea about this.
    Plz ...........

Maybe you are looking for

  • Probleme changing the value of a variable in movieclip from my scene

    Hello, i have a probleme changing the value of a variable in movieclip from my scene. i explain: I have combobox on my scene containing categories, and in the scene i load an xml file containing links to php files that work with the combobox. Also on

  • SP3 Upgrade fails to find Weblogic Server 6.1 installed

    Hello, I have just downloaded SP3 for WLS 6.1. The machine´s im trying to install it on are a Sun box with solaris 8 and an intel box with redhat 7.2, the problem im encounting, when i install the service pack, is that the installer fails to find my

  • Permission Details of Permission Level

    I would need to retrieve permission details of permission level programmatically.  For example:  We have full control , i would like to get what all are the permissions included in the permission level.  I was exploring SProle, SPbasepermission.  The

  • Sequence of Events Fired and Triggers Fired in Forms.

    Hi, Please help me to know how the events and Triggers will be fired in Forms Developer 9i. Thanks in Advance.

  • Weblogic running oracle down

    We have a client appliication making remote calls to weblogic (ejb, jms, etc.). When oracle goes down however, the client locks up, stuck in the remote ejb call. The ejb is likely stuck timing out on the sql connection. Anyhow, this timeout is excess