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