Search code examples
bashapiprocessprogramming-languagesio-redirection

Redirection of stdout to stdin in other languages that BASH when you fork or execute a program


I need to code a program which execute several subprograms, using pipes and redirection. So since I need to use some data structures and functions I want to avoid use Bash for that matter. So far, I know how to use redirection in bash without any problem.

$ ./myprogram -f 1 -h -l < mysource.dat | myprogram2

Some my question are the next:

  1. how can you code this line in other language such as C, Python, Perl, Java or Ruby, avoiding system ("....")?

  2. Also, I wonder which language provide the best process managements tools?


Solution

  • Answer to question 1 in Python:

    from subprocess import Popen, PIPE
    f=file("mysource.dat")
    p1 = Popen(["./myprogram","-f","1","-h"."-l"], stdin=f, stdout=PIPE)
    f.close()
    p2 = Popen(["myprogram2"], stdin=p1.stdout)
    p1.stdout.close()
    p1.wait()
    p2.wait()
    

    More information at the subprocess module documentation.

    Regarding question 2, Java isn't likely to be the best option. C will allow you to use pipe, fork, dup2, and exec system calls to do everything, but involves some more typing. The others are most likely equally good, depending on your personal scripting preferences.