查看 execvp();

Look in execvp();

我刚开始尝试学习 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 来尝试循环,但它不起作用,因为当我编写正确的突击队时程序结束,我需要继续编写突击队因为我需要做一个列出我在程序结束后编写的所有命令。

您的功能的这个特定部分没有按照您的预期进行:

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

需要使用strcmp(),如下:

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

...注意到如果两个参数相等,strcmp() 的 return 值为 0,因此当 a != b 条件为真且循环继续时。

您有一个一般的设计问题:除非出现调用错误,exec 的 none 函数 return 调用方。 shell 的常见设计是伪代码:

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