#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Posts
    245
    Rep Power
    11

    How to call linux commands in c++ program


    Code:
      Hi, how can I run unix/linux command, like ls, rm from a c++ program?
      Thank you.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2004
    Location
    Constant Limbo
    Posts
    989
    Rep Power
    363
    Look into exec* calls.
    Although, before using those calls it is wise to invoke some type of enviroment scrubber.
    True happiness is not getting what you want, it's wanting what you've already got.

    My Blog
  4. #3
  5. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,255
    Rep Power
    2222
    system() is also common. exec* would replace the calling process with a new process (ie, there is no returning from that call), but system() opens a subshell to execute the command you pass it and then returns to the calling process. Please note that any changes system() makes to the environment only applies to the subshell's environment and go away when you exit that subshell, so if you make a series of system() calls where the subsequent calls depend on environment changes made by earlier calls (eg, "cd ..") then you will be unpleasantly surprised at the results. One way around that problem would be to write a shell script to perform that series of operations, then invoke that script through a system() call.

    If you need to read the output of the command, then use popen() to pipe the subshell's stdout to a FILE* in your app. The caveats regarding system() and subshell environments also apply to popen().

    If you use C++'s basic string type to build the command strings that you send, remember that system() and popen() both expect C-style strings, so you will need to use your string's c_str() method in the function calls.

    Also, be aware that many shell commands have counterparts in the C standard library. Like chdir() for cd, mkdir() for mkdir. And unlink() for rm. So you might be able to perform the desired operation programmatically instead of through a subshell. Books and tutorials about UNIX/Linux system programming (or just "Linux Programming") should instruct you in this approach.
    Last edited by dwise1_aol; April 14th, 2006 at 01:48 PM.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2004
    Posts
    103
    Rep Power
    11
    I had a quick question on this subject. I was looking at the man pages and it says do not use system() with "suid or sqid priviledges". Could you shed some light on why they say this?
  8. #5
  9. Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2006
    Posts
    264
    Rep Power
    124
    Originally Posted by L7Sqr
    Look into exec* calls.
    Although, before using those calls it is wise to invoke some type of enviroment scrubber.
    Fork() off a process and invoke exec().
    The environment will be inherited from the parent process, but there are exec() functions that will allow you to modify them if needed.

    Originally Posted by wmsystems.net
    I had a quick question on this subject. I was looking at the man pages and it says do not use system() with "suid or sqid priviledges". Could you shed some light on why they say this?
    Probably because the binary can be easily modified by changing the string literal of the command you are invoking with malicious intent. You wouldn't want to system("ls -l | grep blah"); and have someone modify the literal to be "rm -rf /" if you are running it as root.
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2006
    Posts
    1
    Rep Power
    0

    help


    How to run c++ program in linux?
  12. #7
  13. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,255
    Rep Power
    2222
    Originally Posted by sivaa
    How to run c++ program in linux?
    No, your question is "How to post a new question?"

    Do not tack your question at the end of somebody else's question. Rather, start your own thread.

    Also, there is a "sticky" post at the top of this forum. Read it.


    You cannot "run" a C++ program in Linux. Nor could you in DOS nor under Windows. You have to compile it first and create an executable. Then you run the executable. C++ is not a scripting language.

    Your Linux box should have gcc installed. Running gcc will compile C programs, whereas g++ will compile C++ programs. Assuming your source file is named myprog.cpp:
    g++ myprog.cpp
    If it builds successfully, then it will have created a file, a.out , in that same directory. To run it, enter the command:
    ./a.out
    The "./" is needed to tell the OS that the file is in the current directory.

    If you want the executable to be of a different name, then use the "-o" option; eg:
    g++ -o myprog myprog.cpp

    You should also always develop using the -Wall option (for "warnings: all"); eg:
    g++ -Wall -o myprog myprog.cpp

    If you have more questions, start a new thread.
  14. #8
  15. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2006
    Location
    Albuquerque, NM
    Posts
    120
    Rep Power
    28
    Lets say you want to execute the 'ls' command, the following is a very simple program that will accomplish this:

    C++ Code:
    #include <sys/types.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <stdio.h>
     
    int main( int argc, char **argv ) {
        pid_t child = 0;
        child = fork();
        if (child < 0) {
            fprintf( stderr, "process failed to fork\n" );
            return 1;
        }
        if (child == 0) {
            wait(NULL);
        }
        else {
            execl( "/bin/ls", "ls")
        }
        return 0;
    }


    There are six versions of exec available for linux. You can check them out here . Also, you may want to look into waitpid() and how fork() works. Good luck.
  16. #9
  17. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2008
    Posts
    2
    Rep Power
    0

    Thumbs up Great example! Now how do I grab the output? :D


    weazzle,
    thanks for the excellent example! Its always nice when someone throws a simple example to solidify the idea. I was wondering do you know how to grab the output from the exec? I know there is a way using stdlib "system ()" function but it requires redirecting std:: out or something. Usually the next step after getting a command to execute in code is to grab the output, if you're creating a console app not usually a big deal but if you using a GUI app its a almost must.

    Thanks again
    SuperDonkey

    #include <sys/types.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <stdio.h>

    int main( int argc, char **argv ) {
    pid_t child = 0;
    child = fork();
    if (child < 0) {
    fprintf( stderr, "process failed to fork\n" );
    return 1;
    }
    if (child == 0) {
    wait(NULL);
    }
    else {
    execl( "/bin/ls", "ls")
    }
    return 0;
    }
  18. #10
  19. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2007
    Posts
    765
    Rep Power
    929
    Not only did you tack your question onto a thread where it was explicitly stated that this is improper,
    Originally Posted by dwise1_aol
    No, your question is "How to post a new question?"

    Do not tack your question at the end of somebody else's question. Rather, start your own thread.

    Also, there is a "sticky" post at the top of this forum. Read it.
    but the answer to your question was already posted as well.
    Originally Posted by dwise1_aol
    If you need to read the output of the command, then use popen() to pipe the subshell's stdout to a FILE* in your app. The caveats regarding system() and subshell environments also apply to popen().
    Internet forums, the fastest way to lose faith in humanity.
    sub{*{$::{$_}}{CODE}==$_[0]&& print for(%:: )}->(\&Meh);
  20. #11
  21. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2008
    Posts
    2
    Rep Power
    0
    Sorry
  22. #12
  23. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2007
    Posts
    765
    Rep Power
    929
    It's not that big a deal, just somewhat amusing.

    If you want to stay with the fork & exec method, you can use pipe() and dup2() to connect the stdout of the child to pipe and read it in the parent process.

    Here's a short modification to your code (note that this is 100% untested and that it's been a few years since I did linux programming). Whenever you use pipes, you should also catch SIGPIPE.

    Code:
    #include <sys/types.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <stdio.h>
    
    int main( int argc, char **argv ) {
        pid_t child = 0;
        int pipes[2];
    
        if( pipe( pipes ) != 0 ) {
            fprintf( stderr, "cannot create pipe" );
            return 1;
        }
    
        child = fork();
    
        if (child < 0) {
            fprintf( stderr, "process failed to fork\n" );
            return 1;
        }
        if (child == 0) {
            close( pipes[1] );
            // read from pipes[0] here
            wait(NULL);
        }
        else {
            dup2( pipes[1], 0 );        // 0 is stdout
            close( pipes[0] );
            execl( "/bin/ls", "ls");
        }
        return 0;
    }
    sub{*{$::{$_}}{CODE}==$_[0]&& print for(%:: )}->(\&Meh);
  24. #13
  25. No Profile Picture
    Closet coder
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Feb 2005
    Location
    Plantation, FL <---south florida
    Posts
    1,431
    Rep Power
    153
    also, this thread is 2 years old. if you have a related question start your own thread and link to the old one rather than necro the peaceful dead.

IMN logo majestic logo threadwatch logo seochat tools logo