代码之家  ›  专栏  ›  技术社区  ›  TheAndreyx22

查看execvp();

  •  0
  • TheAndreyx22  · 技术社区  · 6 年前

    我是一个新来的尝试学习fork()函数和系统调用的人,现在我使用execvp()尝试创建bash,但我有一个问题,当我编写正确的命令时,程序会结束,我想创建一个循环来使用bash,直到有人在我的命令行中写入“exit”。 我使用的代码是:

    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <sys/types.h>
    #include <sys/wait.h>
    #include <string.h>
    
    int main()
    {
        char cadena[100];
        char *array[100];
        char *ptr;
        int i=1;
        pid_t pid;
        pid = fork();
    
        if (pid < 0) {
            perror("Error en la llamada a fork().");
            return -1;
        }
        else if (pid == 0) {
            do {
                printf("prompt$ ");
                fgets(cadena, 100, stdin); 
                ptr = strtok(cadena, " \n");
                array[0] = ptr;
                while( (ptr = strtok( NULL, " \n" )) != NULL ){
                    array[i] = ptr;
                    i++;
                }
                array[i]=NULL;
                execvp(array[0],array);
                perror("Execvp failed"); 
            } while(array[0] != "exit");
        }
        else {                                           
            wait(NULL);
        }
        return 0;
    }
    

    我使用迭代结构do while来尝试循环,但它不起作用,因为当我编写正确的commando时,程序将结束,我需要继续编写commandos,因为我需要列出程序结束后编写的所有命令。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Serge Ballesta    6 年前

    您有一个常见的设计问题:除非出现调用错误,否则 exec 函数返回给调用者。外壳的常见设计为伪代码:

    loop
      prompt for a command
      read a command line
      parse the command line
      if exit
         then exit loop
      else
         fork (a child to execute the command, detailed below)
         if pid is 0 (child)
            then exec command
         else
            wait for the child to end
    
        2
  •  1
  •   James McPherson    6 年前

    您的这一特定功能部分并没有实现您的期望:

      }while(array[0] != "exit");
    

    您需要使用 strcmp() ,如下所示:

    } while (strcmp(array[0], "exit"));
    

    。。。注意,返回值来自 strcmp() 如果两个参数相等,则为0,因此当a!=b条件为真,循环继续。