将 Fork 用于命令行参数

Using Fork for Command Line Arguements

我正在尝试执行命令 "ls -l" 但我不确定如何处理它。

这是我试过的:

int main(void) {
    char * input;
    char * args[2];
    char buff[100];

    input = malloc(sizeof(buff));

while(fgets(input,sizeof(input),stdin) != NULL) {

    printf("Enter a command\n");

    if(strcmp(input,"ls -l\n") ==0) {
        pid_t childPid;

        childPid = fork();

        if(childPid == 0) {
            args[0] = "/bin/ls -l";
            args[1] = NULL;

            execv(args[0],args);
    }

}

}

free(input);
}

但是,该命令在这里似乎不起作用。如果我只是简单地使用 "ls" 但我想使用 "ls -l" 它会起作用,我必须传递另一个参数才能让它起作用吗?

当您调用任何 exec() 变体时,您必须分别传递每个参数,如

args[0] = "/bin/ls";
args[1] = "-l";
args[2] = NULL;

首先你必须理解这个简单的例子。

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

int main() {

    /* status of child execution */
    int status;
    /* pointer * to array of char*(strings)*/
    char ** args;

    /* allocate memory for three char*(stings) */
    args = (char**) malloc( 3 * sizeof(char*) );

    /* fork program and store each fork id */
    pid_t childPid = fork();

    /* if this is child process */
    if(childPid == 0) {

        args[0] = "ls";
        args[1] = "-l";
        args[2] = NULL;

        /* execute args[0] command with args arguments */
        execvp(args[0],args);

        /* send execution code 0 to parent and terminate child */
        exit(0);

    } else {

        /* wait execution code from child*/
        wait(&status);

        /* free allocated space */
        free(input);
        free(args);

        /* exit program with received code from child */
        exit(status);
    }

}

我对每一行都进行了评论,但如果您需要更多信息,请告诉我。 在继续用户输入命令之前,您必须了解如何执行来自 child 的命令并通知 parent。