我试图通过模拟Linux shell使用exec()函数执行一个简单的测试 . 测试程序应采用以下形式的命令:cmd arg1 arg2 ...其中cmd是命令,arg1,arg2,...是命令行参数 . 然后exec()函数将调用cmd指定的程序 .

我试过的是:

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

char line[128];
char *args[30];

int main(int argc, char *argv[], char *env[])
{
        // Read command and arguments with fmt: cmd arg1 arg2 ...
        line[strcspn(fgets(line, 128, stdin), "\r\n")] = 0;

        // Tokenize command for input to exec();
        int i = 0;
        args[i] = (char *)strtok(line, " ");
        while(args[++i] = (char *)strtok(NULL, " "));

        if(fork())
        { // Parent
                int *status;
                wait(status);
                printf("Child exit status: %d\n", *status);
                return 0;
        }

        // Child
        int execRV = execve(args[0], args, env);
        printf("execve return value: %d\n", execRV);
        perror(NULL);

        return 0;
}

运行上述程序时,execve()返回错误值-1,perror()的输出为:没有这样的文件或目录 .

在命令行上运行该程序:

gcc -m32 [programName].c
a.out
ls
execve return value: -1
No such file or directory
Child exit status: 0

对于这个例子,主要参数argc和argv无关紧要 . 但是,env参数是Linux环境变量,它包含PATH变量 .