我是刚开始学习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 --当我尝试循环时,它没有工作,因为当我编写正确的命令时,程序结束了,我需要继续写命令,因为我需要用程序结束后编写的所有命令来做一个列表。
发布于 2018-03-27 07:37:30
您有一个一般的设计问题:除非有调用错误,否则所有exec函数都不会返回给调用方。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发布于 2018-03-27 07:36:34
你的职能的这一部分并不是你所希望的:
}while(array[0] != "exit");您需要使用strcmp(),如下所示:
} while (strcmp(array[0], "exit"));..。注意到,如果两个args都相等,则strcmp()的返回值为0,因此当a != b条件为true时,循环将继续。
https://stackoverflow.com/questions/49506319
复制相似问题