Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a bash command from a string in C (without system)

Tags:

c

linux

bash

As the title says, I have a string which contains a bash command given by input(for example, command="ls -l") and I need to execute it from a C program. I know I could simply use system(command), but it's a school exercise and I can't use system, nor popen. I thought about using exec*, but it would require to parse the string to separate the command and the various parameters. Is there a system call (not system) which allows me to simply execute the command with its parameters without having to separate them? Thank you in advance for your answers :)

like image 976
user3523375 Avatar asked Apr 30 '26 03:04

user3523375


2 Answers

This is a way to execute a command without parsing the command and its various parameters:

execl("/bin/sh", "/bin/sh", "-c", "your-command-without-parsing", 0);

First of all, that's not a "bash" command. bash is a shell, but what you have there is a program command line.

You should look into the syscalls

  • fork – used to create a new process
  • execve – used to replace the process image with the program from a different binary.
  • waitpid – used to wait for termination of the forked process

To give you a head start, here's how you launch a shell from your program without invoking system(…):

pid_t spawnshell(void)
{
    char *argv[]={"/bin/sh", 0};
    char *envp[]={0};

    pid_t shpid = fork();
    if(!shpid) {
        execve(argv[0], argv, envp);
        perror("execve");
        assert(0 && "execve failed");
        _exit(-1);
    }

    return shpid;
}
like image 42
datenwolf Avatar answered May 01 '26 20:05

datenwolf