使用Fork进行命令行争论

时间:2016-02-08 00:54:32

标签: c linux process fork

我正在尝试执行命令“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”它是否有另外一个参数我必须通过才能使它工作?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

首先,您必须了解这个简单的例子。

#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);
    }

}

我评论了每一行,但告诉我你是否想要更多的信息。 您必须了解如何从子进行命令并在继续使用用户的输入命令之前通知父进程。

相关问题