C语言中fork()和execvp()的奇怪行为

时间:2012-05-19 20:20:31

标签: c shell exec fork

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

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&gt; 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

0 个答案:

没有答案