如何使用参数在linux中的C代码中执行外部程序?

时间:2011-03-08 19:49:44

标签: c linux

我想在C代码中执行另一个程序。 例如,我想执行一个命令

./foo 1 2 3

foo是存在于同一文件夹中的程序,1 2 3是参数。 foo程序会创建一个将在我的代码中使用的文件。

我该怎么做?

7 个答案:

答案 0 :(得分:40)

简单来说,使用system()

#include <stdlib.h>
...
int status = system("./foo 1 2 3");

system()将等待foo完成执行,然后返回一个状态变量,您可以使用该变量来检查,例如exitcode(命令的exitcode乘以256,所以将system()的返回值除以得到实际的exitcode:int exitcode = status / 256)。

The manpage for wait()(在第2部分,Linux系统上为man 2 wait)列出了可用于检查状态的各种宏,最有趣的是WIFEXITED和{{1 }}

或者,如果您需要读取foo的标准输出,请使用WEXITSTATUS,它返回文件指针(popen(3));与命令的标准输入/输出交互与读取或写入文件相同。

答案 1 :(得分:33)

system函数调用shell来运行命令。虽然这很方便,但众所周知security implications。如果您可以完全指定要执行的程序或脚本的路径,并且可以承受失去system提供的平台独立性,那么您可以使用execve包装器,如{ {1}}以下功能可以更安全地执行您的程序。

以下是如何在调用者中指定参数:

exec_prog

然后像这样调用const char *my_argv[64] = {"/foo/bar/baz" , "-foo" , "-bar" , NULL}; 函数:

exec_prog

这里是int rc = exec_prog(my_argv); 功能:

exec_prog

记住包括:

static int exec_prog(const char **argv)
{
    pid_t   my_pid;
    int     status, timeout /* unused ifdef WAIT_FOR_COMPLETION */;

    if (0 == (my_pid = fork())) {
            if (-1 == execve(argv[0], (char **)argv , NULL)) {
                    perror("child process execve failed [%m]");
                    return -1;
            }
    }

#ifdef WAIT_FOR_COMPLETION
    timeout = 1000;

    while (0 == waitpid(my_pid , &status , WNOHANG)) {
            if ( --timeout < 0 ) {
                    perror("timeout");
                    return -1;
            }
            sleep(1);
    }

    printf("%s WEXITSTATUS %d WIFEXITED %d [status %d]\n",
            argv[0], WEXITSTATUS(status), WIFEXITED(status), status);

    if (1 != WIFEXITED(status) || 0 != WEXITSTATUS(status)) {
            perror("%s failed, halt system");
            return -1;
    }

#endif
    return 0;
}

有关需要通过#include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> stdin等文件描述符与已执行程序进行通信的情况,请参阅related SE post

答案 2 :(得分:15)

您可以使用fork()system(),这样您的程序就不必等到system()返回。

#include <stdio.h>
#include <stdlib.h>

int main(int argc,char* argv[]){

    int status;

    // By calling fork(), a child process will be created as a exact duplicate of the calling process.
    // Search for fork() (maybe "man fork" on Linux) for more information.
    if(fork() == 0){ 
        // Child process will return 0 from fork()
        printf("I'm the child process.\n");
        status = system("my_app");
        exit(0);
    }else{
        // Parent process will return a non-zero value from fork()
        printf("I'm the parent.\n");
    }

    printf("This is my main program and it will continue running and doing anything i want to...\n");

    return 0;
}

答案 3 :(得分:4)

在C

#include <stdlib.h>

system("./foo 1 2 3");

在C ++中

#include <cstdlib>

std::system("./foo 1 2 3");

然后照常打开并阅读文件。

答案 4 :(得分:4)

system()执行一个shell,然后负责解析参数并执行所需的程序。要直接执行程序,请使用fork()和exec()(这是system()用来执行shell以及shell本身用于执行命令的内容)。

#include <unistd.h>

int main() {
     if (fork() == 0) {
          /*
           * fork() returns 0 to the child process
           * and the child's PID to the parent.
           */
          execl("/path/to/foo", "foo", "arg1", "arg2", "arg3", 0);
          /*
           * We woundn't still be here if execl() was successful,
           * so a non-zero exit value is appropriate.
           */
          return 1;
     }

     return 0;
}

答案 5 :(得分:2)

这样怎么样:

char* cmd = "./foo 1 2 3";
system(cmd);

答案 6 :(得分:1)

当你没有硬编码的args时,这是扩展到变量args的方法(尽管在这个例子中它们仍然在技术上是硬编码的,但应该很容易弄清楚如何扩展......):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int argcount = 3;
const char* args[] = {"1", "2", "3"};
const char* binary_name = "mybinaryname";
char myoutput_array[5000];

sprintf(myoutput_array, "%s", binary_name);
for(int i = 0; i < argcount; ++i)
{
    strcat(myoutput_array, " ");
    strcat(myoutput_array, args[i]);
}
system(myoutput_array);