0

在我之前的帖子中发表了一些评论后,我做了以下修改:

int main()
{
char errorStr[BUFF3];
 while (1)
 {

     int i , errorFile;

     char *line = malloc(BUFFER);
     char *origLine = line;
     fgets(line, 128, stdin);   // get a line from stdin

     // get complete diagnostics on the given string
     lineData info = runDiagnostics(line);

     char command[20];
     sscanf(line, "%20s ", command);
     line = strchr(line, ' ');          // here I remove the command from the line , the command is stored in "commmand" above

     printf("The Command is: %s\n", command);

     int currentCount = 0;                  // number of elements in the line
     int *argumentsCount = &currentCount;   // pointer to that

     // get the elements separated
     char** arguments = separateLineGetElements(line,argumentsCount);

     printf("\nOutput after separating the given line from the user\n");
     for (i = 0; i < *argumentsCount; i++) {
         printf("Argument %i is: %s\n", i, arguments[i]);
     }

     // here we call a method that would execute the commands
     pid_t pid ;

     if (-1 == (pid = fork()))
     {
        sprintf(errorStr,"fork: %s\n",strerror(errno));
        write(errorFile,errorStr,strlen(errorStr + 1));
        perror("fork");
        exit(1);
     }
     else if (pid == 0)  // fork was successful
     {
        printf("\nIn son process\n");

        // if (execvp(arguments[0],arguments)  < 0)       // for the moment I ignore this line
        if (execvp(command,arguments)  < 0)       // execute the command
        {
            perror("execvp");
            printf("ERROR: execvp failed\n");
            exit(1);
        }
     }
     else // parent
     {
        int status = 0;
        pid = wait(&status);
        printf("Process %d returned with status %d.", pid, status);
     }

     // print each element of the line
     for (i = 0; i < *argumentsCount; i++) {
         printf("Argument %i is: %s\n", i, arguments[i]);
     }

     // free all the elements from the memory
     for (i = 0; i < *argumentsCount; i++) {
         free(arguments[i]);
     }

     free(arguments);
     free(origLine);
 }

 return 0;
}

当我进入控制台时: ls > out.txt

我得到:

The Command is: ls
execvp: No such file or directory
In son process
ERROR: execvp failed
Process 4047 returned with status 256.Argument 0 is: >
Argument 1 is: out.txt

所以我猜这个子进程是活跃的,但由于某种原因execvp失败了。

为什么 ?

问候

评论 :

ls命令只是一个示例。我需要使它适用于任何给定的命令。

编辑 1:

用户输入:ls > qq.out 程序输出:

The Command is: ls

Output after separating the given line from the user
Argument 0 is: >
Argument 1 is: qq.out

In son process
>: cannot access qq.out: No such file or directory
Process 4885 returned with status 512.Argument 0 is: >
Argument 1 is: qq.out
4

0 回答 0