【发布时间】:2020-11-07 19:25:11
【问题描述】:
我正在制作简单的 shell 程序并尝试在用户输入“exit”时退出它,并且我尝试了一些不同的关键字,例如 exit()、return 0、break;
这是我的代码:
void read_command(char path[], char *args[], char input[]) {
char *array[MAX], *ptr;
char *inputptr;
if ((inputptr = strchr(input, '\n')) != NULL) {
*inputptr = '\0';
}
int i = 0;
char *p = strtok(input, " ");
while (p != NULL) {
array[i++] = p;
p = strtok(NULL, " ");
}
for (int j = 0; j < i; j++) {
args[j] = array[j];
}
}
int main() {
char path[MAX];
char *args[MAX] = {NULL};
int status;
char input[MAX];
while (TRUE) {
printf(">> ");
fgets(input, sizeof(input), stdin);
if (fork() != 0) {
if (waitpid(-1, &status, 0) < 0) {
perror("waitpid error ");
}
} else {
read_command(path, args, input);
if (strcmp(input, "exit") == 0) {
exit(0);
}
strcpy(path, "/bin/");
strcat(path, args[0]);
if (execve(path, args, 0) < 0) {
perror("exec error ");
return EXIT_FAILURE;
}
}
}
return EXIT_SUCCESS;
}
当我返回 strcomp() 值时,它确实给了我 0,所以我不确定为什么它不工作,程序似乎完全忽略了退出语句,只是继续执行代码,有人可以解释一下我该怎么做这?谢谢。
【问题讨论】:
-
记住,当你分叉时,你有两个进程从另一边出来。他们都需要退出。
标签: c linux bash shell system-calls