How can I avoid the variables sent to the "system" command in C ++?

This question talks about using the command systemand passing variables. Here is an example that he gives:

string cmd("curl -b cookie.txt -d test=");
cmd += line;
cmd += "  http://example.com";
system(cmd.c_str());

One comment mentions that if lineit was transmitted and contained foo & fire_nukes.exe & REM, then it is entirely possible that something bad could happen.

PHP has an excellent function escape_shell_argsthat can be used to remove parameters passed to a program. Is there a way for C ++ to do this?

+5
source share
4 answers

The best way is not to use system()at all. Use fork()and exec()and friends. Here is an example:

#include <string>
#include <unistd.h>
#include <error.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <cstdlib>

int fork_curl(char *line)
{
    std::string linearg("line=");
    linearg += line;

    int pid = fork();
    if(pid != 0) {
        /* We're in the parent process, return the child pid. */
        return pid;
    }
    /* Otherwise, we're in the child process, so let exec curl. */

    execlp("curl", "-b", "cookie.txt", "-d", linearg.c_str());  
    /* exec is not supposed to return, so something
       must have gone wrong. */
    exit(100);
    /* Note: You should probably use an exit  status
       that doesn't collide with these used by curl, if possible. */
}

int main(int argc, char* argv[])
{
    int cpid = fork_curl("test");
    if(cpid == -1) {
        /* Failed to fork */
        error(1, errno, "Fork failed");
        return 1;
    }

    /* Optionally, wait for the child to exit and get
       the exit status. */
    int status;
    waitpid(cpid, &status, 0);
    if(! WIFEXITED(status)) {
        error(1, 0, "The child was killed or segfaulted or something\n");
    }

    status = WEXITSTATUS(status);
    /* Status now contains the exit status of the child process. */
}
+4
source

system. -.

, , , , .

: , switch .

, , - , , , . libcurl, -?

+4

execl..

http://linux.about.com/library/cmd/blcmdl3_execvp.htm

#include <unistd.h> 

int execl(const char *path, const char *arg, ...); 
0

. , syscalls ( - system(3), ).

linux kernel,

, ( , , , ).

. fork, execve ..

Linux- Advanced Unix

Use the freedom of most programs in a Linux distribution. For example, you can study the source code of a simple shell, for example sash.

And maybe you just want to use curl. Then the best way is the libcurl code library (without calling system(3))

Have fun exploring all of this!

0
source

All Articles