Calling Shell commands in C programme

How would i call shell command using C programme.

#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/types.h>
#include <wait.h>
int main(void) {
pid_t pid;
pid = fork();
if (pid == 0) {
execl("/bin/sh", "sh", "-c", "/bin/ls -l > /tmp/ls", NULL);
exit(1);
else if (pid > 0) {
wait(NULL);
else {
return -1;
return 0;
}

Similar Messages

  • How can i call shell command in JSP?

    My OS is Linux, and my WWW server is Tomcat,
    can i call shell command , such as gcc or setup,
    If yes, how can i? Would you give a source example?
    Thank you!

    Hi,
    I did this simple class to launch a process and after the cose there is an example to use it:
    import java.io.*;
    import java.util.*;
    public class ProcessExec {
    private String[] command;
    private StreamGobbler errorGobbler;
    private StreamGobbler outputGobbler;
    public ProcessExec() {
    public ProcessExec ( String[] command) {
    this.command = command;
    this.errorGobbler = null;
    this.outputGobbler = null;
    public String[] getCommand() {
    return ( this.command );
    public void setCommand( String[] command ) {
    this.command = command;
    public void exec() {
    try{
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(this.command);
    // any error message?
    errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
    // any output?
    outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
    // kick them off
    errorGobbler.start();
    outputGobbler.start();
    }catch (Throwable t){
    t.printStackTrace();
    }//catch
    public String getErrorMessage() {
    while ( this.errorGobbler.isAlive() ) {;}
    return ( this.errorGobbler.getResult().toString() );
    public String getOutputMessage() {
    while ( this.outputGobbler.isAlive() ) {;}
    return ( this.outputGobbler.getResult().toString() );
    } // ProcessExec
    Example to use it:
    try {
    ProcessExec pe = new ProcessExec( command );
    pe.exec();
    errorMessage = pe.getErrorMessage();
    outputMessage = pe.getOutputMessage();
    } catch ( Exception e ) {
    System.out.println (e);
    As you can guess the string "command" must be the command you have to launch and errorMessage and outputMessage will contain the error and the output that the process will generate.
    Try it; i hope this will help you.
    Cheers.
    Stefano

  • Calling a shell command from LabVIEW

    Platform:
    Labview 8.6 on Fedora 10.
    The VI is generating some data that I wish to convert to a form that a Windows user can work with (with CR/LF as the EOL). Is there a way to issue a shell command (specifically: $unix2dos <generated file name>) from within labview ? 
    Solved!
    Go to Solution.

    Hi,
    have you tried the "System Exec" function? According to context help it should work on UNIX too...
    Btw. you have asked a related question in an other thread. Wouldn't converting the string data in the VI itself work? Or making a special VI for that purpose and enable the conversion by a switch (like "Win compatible format?")?
    Message Edited by GerdW on 02-13-2010 09:38 AM
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • IS there an easy way to execute a shell command and capture its output...

    From an application? I am thinking of using fork and then waiting for the PID to finish and write the output to a file which I then read, but this seems clunky. Also there are big warnings about frameworks getting hosed if you use fork, although the "Forked" process will exec the shell command and the one that gets the PID the original process might be 'safe' from this framework corruption. I am not certain of this, it is just a guess.
    If there was something like a process class where I could specify the executable and parameters, and read from it's std out until the process completed, that would be better. Or even get a callback when the process exited and an asynchronous callback for each line of data it produced.

    That was just in response to OrangeKay implied accusation that I was some kind of hard-core Microsoft programmer that sneered at apple programmers.
    You may want to book mark this, I will go over a brief history which should clear a lot of things up, about me, and about what I am doing.
    Lets turn the clock back to 1998: I graduate from a university with a BS in Computer science. I had been interning at a local defense contractor writing missile testing software. This was on a proprietary hardware and so there was no "Microsoft" involved. At this point I think Bill Gates = Satan. Microsoft = Kingdom of Evil.
    I get a job as a video game programmer. I write code from the Playstation, then the Playstation 2 and Gamecube. I do this for several years and again I have zero interest / knowledge of the Microsoft world beyond it being the OS which I am forced to use to play my games on. I had fought this by trying to use OS Warp and other things, but eventually since I mainly had a PC for games I had to get a windows OS, the first being NT 3.51 and then Win98 cause NT4.0 didn't support past directx 3 and everyone was using directX 5 or 6 (I do not remember).
    As video game companies go, they do not last. Everyone wants to write video games, anyone with some cash wants to start a company. 1 in 1000 will make it 5 years. Needless to say, as our company began to tank, I got laid off, along with my entire team. I have cash in the bank, no big deal, right?
    Well the economy started to suck, video game developers were closing down like crazy so the market was saturated with x-video game developers. 2 Years go by, no job, and almost no money. Then I get a call from some guy who wants me to come for an interview about 75 miles away. It is in a place I do not want to go. So they interview me, and ask me a bunch of general programming questions.
    I leave the place, and by the time I get home there is a message on my machine asking me if I would take the job at a ridiculously high salary (I live in an area where the cost of living is very low). Well I am about out of money and its a job offer with a huge salary, so I take it.
    I get there and guess what? I get to work on this "agent" that runs on windows boxes. I have NO IDEA how to program on windows. Windows is evil, why would I want to taint myself with this vile Microsoft APIs? I really have no choice, I have to learn how to develop on windows. I get to use visual studio 6, which I do not understand because I used the Borland compilers (Borland != Microsoft).
    Well I start to slug through it all and get familiar with MSDN and CodeProject and CodeGuru. As the years pass, I begining applicate the examples and detailed documentation that MSDN has. I have a start page on MSDN which covers every category of operation which will take you through a tree of choices and lead you to the exact area related API calls you will need to use to do whatever you want. Now I do not think MS = Evil anymore. I switch to DevStudio 2005 which is really nice. The debugging, IDE, and everything is great.
    Now the other half of this application resides on a server. That server is a Linux box, and the server app is written in Java. My stuff is still C++.
    One day, I get a request, and a eMac with 10.4 PPC to make a Mac version. Now I am at the point of Mac programming as I was with Windows when I started. I didn't know anything about it. I was looking for CodeWarrior cause I used that in the past, but alas, CodeWarrior is no more. I get XCode. I see all sorts of options to make a project. BSD project, Carbon, Cocoa, etc... What the heck any of these. I can guess the BSD one is very basic, but I do not understand Carbon vs Cocoa.
    So what do I do? I make a basic carbon app and make a basic Cocoa app. The carbon app looks like some kind of C++ framework. The Cocoa app? "Is this another language like Java or C#? It doesn't look like a C++ language."
    Guess which choice I make. Carbon. I struggle through this looking at the docs, posting on CodeGuru and whatnot until someone finally tells me about these forums and warns me about how unfriendly people are. So I make an account and start asking questions. I eventually get my app to be multi-platform to run on windows and Mac by using some API abstractions which are easy to do since I had abstracted the Windows API by my own class wrappers.
    I ask a lot of questions, very few are ever answered because I am not asking about simple things, like making windows and how to get button clicks and that stuff. I am asking stuff like, "How do you change the DNS? or How do I know when a user is about to log out?" Currently on my side list as I type this, I have 27 unresolved questions. I probably found workaround for most of them, or figured it out eventually.
    On this forum mostly people are helpful when the do respond, except for OrangeKay. He definitely has a chip on his shoulder.
    Over the past few years my Opinion of MS has improved greatly while my opinion of Macs (from the programmer's point of view) has dropped considerably. XCode still isn't as good as VS6 which is like 15 years old, never mind Dev studio 2005 or 2008. The documentation is scattered, not easy to find, occasionally wrong, or simply missing. The examples may not even compile or contain non-existent functions. It is unbelievable how bad it is.
    If Steve Jobbs wants to really get a large coder population he ought to spend some of those billions (or is it trillions) of dollars on a team that will re-write the current documentation in a correct, easy to understand, with full examples, arranged in a logical manner for everyone to use. He should say, "See MSDN online? I want something like that, only better, it has to be MUCH better." Then he should say to the XCode team, "Look at DevStudio 2008. XCode should do EVERYTHING that does. Once that is done, IMPROVE XCode even more to make 2008 look like a joke."
    To bad the Developer aspect of the "Apple Experience" has not gotten "End User" treatment. Then it would be a joy to develop on Macs.
    So here I am asking for help on certain things. You wonder why I do not use Cocoa. Maybe I should, maybe I shouldn't. My first look didn't look promising, and a quick look at the docs is all about GUI's. My app has NO GUI. Again, Cocoa? Maybe it will still work, but the examples and stuff I see are all about GUIs.
    When I get time, I will look at cocoa even further. MFC on windows is MOSTLY about GUI stuff, but there is a small section of it that does not deal with GUIs. CString is a great MFC class. I had to get rid of it though cause Mac's do not have a similar class. I use CStdString which is a platform agnostic CString replacement.
    I hope you are all a little more enlightened. BTW my Application which runs on Mac's and PCs on no less then 3 MILLION Machines has not crashed ONCE in the past 2 years. There have been bugs, but nothing that crashed it. The bugs were mostly unforeseen situations, like what if the guy has 15 network adapters that are all LIVE? I didn't plan for that, there were complications, the server got some strange data, but it didn't crash (My app, not the server. It crashes on occasion still). Are there bugs in my code? I am sure there are, but I do not know of any, because if I did, it would be fixed.

  • Run shell commands using java program

    Hi guys,
    I am trying to run shell commands like cd /something and ./command with arguments as follows, but getting an exception that ./command not found.Instead of changing directory using "cd" command I am passing directory as an argument in rt,exec().
    String []cmd={"./command","arg1", "arg2", "arg3"};
    File file= new File("/path");
    try{
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(cmd,null,file);
    proc.waitFor();
    System.out.println(proc.exitValue())
    BufferedReader buf = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    catch(Exception e)
    {e.printStackTrace();
    So can anyone please tell me what is wrong with this approach? or is there any better way to do this?
    Thanks,
    Hardik

    warnerja wrote:
    What gives you the idea that the process to execute is called "./command"? If this is in Windows, it is "cmd.exe" for example.It does not have to be cmd.exe in Windows. Any executable or .bat file can be executed as long as one either specifies the full path or the executable is in a directory that is in the PATH.
    On *nix the file has to have the executable bit set and one either specifies the full path or the executable must be in a directory that is in the PATH . If the executable is a script then if there is a hash-bang (#!) at the start of the first line then the rest of the line is taken as the interpreter  to use. For example #!/bin/bash or #!/usr/bin/perl .
    One both window and *nix one can exec() an interpreter directly and then pass the commands into the process stdin. The advantage of doing this is that one can change the environment in one line and it  remains in effect for subsequent line. A simple example of this for bash on Linux is
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    public class ExecInputThroughStdin
        public static void main(String args[]) throws Exception
            final Process process = Runtime.getRuntime().exec("bash");
            new Thread(new PipeInputStreamToOutputStreamRunnable(process.getErrorStream(), System.err)).start();
            new Thread(new PipeInputStreamToOutputStreamRunnable(process.getInputStream(), System.out)).start();
            final Writer stdin = new OutputStreamWriter(process.getOutputStream());
            stdin.write("xemacs&\n");
            stdin.write("cd ~/work\n");
            stdin.write("dir\n");
            stdin.write("ls\n");
            stdin.write("gobbldygook\n"); // Forces output to stderr
            stdin.write("echo $PATH\n");
            stdin.write("pwd\n");
            stdin.write("df -k\n");
            stdin.write("ifconfig\n");
            stdin.write("echo $CWD\n");
            stdin.write("dir\n");
            stdin.write("cd ~/work/jlib\n");
            stdin.write("dir\n");
            stdin.write("cat /etc/bash.bashrc\n");
            stdin.close();
            final int exitVal = process.waitFor();
            System.out.println("Exit value: " + exitVal);
    }One can use the same approach with Windows using cmd.exe but then one must be aware of the syntactic differences between commands running in .bat file and command run from the command line. Reading 'help cmd' s essential here.
    The class PipeInputStreamToOutputStreamRunnable in the above example just copies an InputStream to an OutputStream and I use
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    public class PipeInputStreamToOutputStreamRunnable implements Runnable
        public PipeInputStreamToOutputStreamRunnable(InputStream is, OutputStream os)
            is_ = is;
            os_ = os;
        public void run()
            try
                final byte[] buffer = new byte[1024];
                for (int count = 0; (count = is_.read(buffer)) >= 0;)
                    os_.write(buffer, 0, count);
            } catch (IOException e)
                e.printStackTrace();
        private final InputStream is_;
        private final OutputStream os_;
    }

  • Executing shell commands from Java.

    I want to execute shell commands in Java using the Runtime.exec( String ) method.
    The method works fine under Linux OS, but under Windows '98 the method didn't work at all!
    For example the following call: Runtime.exec( "dir" ) throws an exception showing that the command was not completed. If I replace dir with ls under Linux all is good. What is the problem with the Microsoft Windows '98 ? Is there any solution at my problem ?!
    thx in advance!

    hey JSarmis,
    You can help me... "ls" doesn't work for me on linux.. using Runtime.exec, some commands work, others don't... you may hold the key to what i need? How did u get "ls" to work?

  • Running Shell Commands (not Executable) in Unix from Java

    What are my options to run shell commands from Java?
    My goal is to change my existing shell environment variables to some new ones provided by .anotherProfile.
    Using an executable from Java is not an option because it does not work i.e. ( exec(". /home/.profile") ) brings up errors.
    Someone has suggested that I start a child shell with that profile and work from there, but I'm unfamiliar with that sort of syntax and programming in general.
    Any good help equals duke dollars :)

    Well there are some possibilities. In the original thread you mentioned that you wanted the shell script to be executed to change some enviroment parameters of the shell the JVM is executing in.
    If so, and you are able to rewrite the profile so you can parse it manually. Then you can change some environment setting by writing the JNI wrappers for the getenv and setenv system calls. (Check your man pages)
    That will change the environment. I am just wondering what good it will do for you? What's use of sourcing the profile in a JVM?

  • Call unix command in sqlplus script

    Hello, I wanna to know how to call a unix command in the sqlplus script.
    For exemple,
    I've a sqlplus script to lauch a oracle report, after the report is generated, I wanne to replace the output file in an other directory.
    So that, I have to call the unix command mv here in the sqlplus script
    How can I do it?**
    I completed my situation:
    I don't have dbms_scheduler untility in my database.
    Thanks a lot for your help
    Edited by: user11930885 on 17 janv. 2010 14:53

    Yes, at the begining, I'll tried the unix shell by calling SQL.
    I've the problem of passing the parameters through.
    It seems to me
    we can use
    Host in the SQLPLUS to run the unix command.
    but I've written it in my sqlplus script, it doesn't work. so I wanna to find an exemple how to use HOST in sqlplus script?
    I would have loved to give you an example..but its not unix on my laptop.
    But what i can tell you is...u should be doing otherway round.
    Not calling Unix commands from SQL but calling SQL's form unix.
    You got shell scripts for that.
    Write a shell script. Login to SQL execute your code.
    exit from sql and then move your file with MV. That's it.
    Do post how far you get after trying this.

  • Calling CL command in java

    I would like to know how to call cl command in java to delete a file in my server. thanks

    Use the java.lang.Runtime interface. The exec() method allows you to execute commands from the command shell:
    String cmd = new String[2];
    cmd[0] = "cl";
    cmd[1] = fileToDelete;
    Runtime rt = Runtime.getRuntime();
    rt.exec(cmd);

  • Calling shell script from sql procedure

    Hi gurus
    Is it possible
    1)to call a shell script from sql procedure
    2)that shell script has to return one value
    3)and again sql procedure(calling shell script) has to capture the return value.
    please help me to write this script

    You may NOT have EXECUTE privilege/ permissions on the DBMS_PIPE package. Check with your DBA.
    Using DBMS_PIPE may not be that simple to implement. Just making a call to DBMS_PIPE procedure will not do anything. It will NOT trigger anything on the UNIX side.
    . You will also need to :
    1.     Write a job (ie CRON) at UNIX side which will keep read the incoming pipe for new messages, Unpack the message and get the command to be executed at the UNIX side -- There will be a lot of work involved here + DBA presence/activity is also required.
    As Justin has pointed out, try and use HOST command which is very simple or try and use Java.
    Shailender Mehta

  • Executing shell command

    hi
    i waould like to know if any one can tell me how to execute a shell command or call an from within a class file.
    i am required to write a program which creates a servlet file internally everytime it is run.
    i want to know how to execute the shell command in java so that i can compile that file after creating the file from within the class file and not leave it to the user to do it.

    Runtime.getRuntime().exec("<your_command>");

  • Shell command - making Director continue whilst shell takes place

    Hi
    a quick question on Shelling -
    on a pc if i use Buddy API to Shell a command or run a bat file then i can have the Director app continue whilst the utility that I called takes place.
    However, that function doesn't work on the mac
    so i use Valentin Schmidt's shell.xtra
    which is great, and also seems to have a Callback function so I'd imagine that it allows for things to continue whilst the shell command takes place.
    But it doesn't seem to at least not when I try to create a disk image with the hdiutil command
    eg.
    tscript="echo -n $pw | hdiutil create -srcfolder '$src' -encryption -stdinpass -fs HFS+ -volname '$imagename' '$destimage'"
    shell_cmd(tscript)
    Since creating a disk image can take a while I'd rather Director continue and then I can at least monitor the size of the image as its created. Or let the user get on with using the app.
    At the moment Director is just frozen and if the image is large enough (eg 4GB) then it freezes entirely and needs a force quit.
    Has anyone had any experience of this?
    Presumably another option might be to write a script with the appropriate extension (like a bat file in Windows) and then open it with the open... with... command (beacuse then its running outside of Director) but I thought I'd try the neater method first.
    Thanks

    Hi Mike
    yes, asynchronous is what I'm after!
    unfortunately that asynch cmd (i've just looked at the windows readme and its called shell_cmd_thread) doesn't seem to be available in the Mac version. (v05, ie for Dir 11, which is I think the latest)
    all i get (according to the readme) is
    INTERFACE
    *shell_cmd string, *
    *shell_cmd_list string
    -- Utilities for path conversion
    *shell_hfs2posix string
    *shell_posix2hfs string
    He doesn't list it as a difference to the Win version but I've tried shell_cmd_asynch and I've tried shell_cmd_thread and that handler isn't defined on the mac.
    Thanks for the tip anyway. i will go down the batch file route, whatever that may be on a mac...

  • How to call gnuplot command from java

    Hi there,
    In our course, we are required to develop an GUI for gnuplot. In case you don't know about gnuplot, it's a plotting program and has lots of command. We want to use java and swing, but now we don't know how to call gnuplot command from java, or how to execute a shell command(script) from java.
    By the way, since we need read in files with several columns of data and allow user to select a column, we want to use JTable. Is that reasonable?
    Thanks a lot for any suggestions!
    Jack

    Hi, there:
    Will using JTable add much overhead? I may have to use several JTables and switch among them. I can add scroll bar to or edit JTables, right?
    BTW, do you have experience about gnuplot? Can I find the command tree of gnuplot somewhere? Or do you know a better place to post question about gnuplot? unix/linux group, maybe.
    Thanks,
    Jack
    P.S. Would you guys answer my question after I use up my duke dollars? :- )

  • Custom keybinding for shell command in emacs

    Hello all,
    I am a very frequent LaTeX user, and I often have BibTeX references and pstricks images, so I end up compiling my document several times for every document. To speed up this process, I wrote a short, simple shell script (below)
    #!/bin/sh
    file="$1"
    latex \\nonstopmode\\input $file.tex
    bibtex $file
    latex \\nonstopmode\\input $file.tex
    latex \\nonstopmode\\input $file.tex
    dvips $file.dvi
    ps2pdf $file.ps
    This has been much nicer, since instead of typing all of those things, I simply type "mytex file."
    Being the greedy person that I am, I would now like to compile it from emacs without typing the shell command, kind of like C-c C-f when I am just compiling as usual. I don't have very much experience with custom keybindings in emacs anyway, but I certaintly do not know how to call a particular shell command including the current file name.
    Any tips?
    Last edited by keither (2010-02-15 15:18:42)

    First of all, you will probably save some compilation time by using an "inteligent" script such as latexmk. You should look into it if you have not done so already.
    Second of all, AUCTeX will also suggest the "correct" next step when using C-c C-c. Also, you should consider just adding latexmk or your own script to the C-c C-c cycle. Here are some examples from my .emacs
    (eval-after-load "tex"
    '(progn
    (add-to-list 'TeX-command-list
    (list "View in Acrobat Reader" "acroread %o"
    'TeX-run-command nil t))
    (add-to-list 'TeX-command-list
    (list "Count Words" "texcount -inc %s.tex"
    'TeX-run-command nil t))
    (add-to-list 'TeX-command-list
    '("Synctex" "/home/rasmus/.scripts/synctex-emacs %t %b %n" TeX-run-TeX nil t) t)
    If you want to use a script as the one suggested by yourself you would want to look into the last exampe ("Synctex").
    --Rasmus

  • How to call dos commands through HTMLDB buttons

    HI,
    How do i call DOS commands through HTMLDB buttons, or on any process?
    can anyone help me on this?
    THANKS!
    BROKEN

    This article explains how to execute shell commands from whitin pl/sql using java (in the database).
    http://www.oracle-base.com/articles/8i/ShellCommandsFromPLSQL.php
    It is for Oracle8i but should still work. This still looks like a good way to go.
    ~Dietmar.

Maybe you are looking for

  • Transaction/report for list of PGI with sales total price details

    Sir/madam, After making PGI we want to know the total sales price for that material. We want list of all details of price/value. Before making invoice we want to know the total price listing with sales order details. We get this one by one with VF01

  • Export an XML file from oracle database

    plz help me its urgent requirement....could u pls tell me the step by step procedure for following questions...?how to export a data as an XML file from oracle database? is it possible..? thanks in advance, Bala. is it possible? Edited by: user352329

  • Trouble with Adobe Flash 11 functioning after install

    After installing Adobe Flash Player 11 and receiving confirmation, it still will not function when trying to view video. Have removed previous program, followed instructions and tried install several times and still no luck.

  • PowerBI regional/localisation settings (date time format/timezone) - PowerPivot dax NOW() returning UTC date

    Can the regional settings be changed for PowerBI or are we stuck with UTC? Tried googling but the only hits for 'regional powerbi' relate to the portal being available in that region, not any kind of localisation configuration I have a workbook that

  • Logic Express Vs. The motherload!

    I wish there was a comparison forum for logic express vs. pro, but since there isn't I choose one randomly and am asking what logic pro has that logic express doesn't...? (besides a price range that is 700 bucks higher) Paulie