当前位置: 动力学知识库 > 问答 > 编程问答 >

How can I execute a Bash program from C?

问题描述:

This question already has an answer here:

  • Is it possible to include a shell program in a c program

    1 answer

网友答案:

Case1 : script from a file - Use the shebang

#!/usr/bin/env bash

at the top of your script and then do

int status=system("/full/path/to/script");
if(status==-1){
// failure mode
}

Case2 : script stored as a string

Do something like below

char *command="$(which bash) -c 'ls'";
int status=system(command);
if (status==-1){
  //failure mode
}
网友答案:

If you're creating a very long shell command and you need bash to interpret it, then you have two real options:

  1. Save the text into a file and invoke bash with the filename as a single argument (equivalently, use a shebang in the file to specify bash as the interpreter, make the file executable, and invoke that as command), or
  2. Start an instance of bash with popen() and write the shell command as standard input to the bash process.

If you're having problems due to shell script quoting (rather than the command length), then either of those options would work, or you could implement the equivalent of system() but using execl() to pass the argument without going through sh. I'm assuming a POSIX-type system here.

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


int run_bash(const char *command)
{
    int pid = fork();

    if (pid < 0) {
        /* failed */
        perror("fork");
        return pid;
    } else if (pid == 0) {
        /* child */
        execl("/bin/bash", "bash", "-c", command, (char*)NULL);
        perror("exec");
        exit(EXIT_FAILURE);
    } else {
        /* parent */
        int status;
        do {
            waitpid(pid, &status, 0);
        } while (!WIFEXITED(status));
        return WEXITSTATUS(status);
    }
}

int main(void)
{
    run_bash("echo '*'");
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: