0

我正在尝试通过模拟 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() 的输出为:No such file or directory。

在命令行上运行程序:

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 变量。

4

0 回答 0