我正在尝试实现我自己的 shell,有很多东西无法在其中工作,但现在我正在尝试解决第一个错误。 当我的 shell 正在运行并且我输入 exit 作为第一个命令时,它工作正常,但是,当我输入 exit 作为第二个输入时,如果我将其作为第三个命令输入,我应该额外编写 exit 一次以使其退出我的 shell ,我必须额外输入两次,依此类推。 这是我的代码。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int argumentsnum;
int status;
char *arguments[30];
char *temp;
int processes_count=0;
printf("My Shell\n");
while (1)
{
char input[60];
printf("Enter command\n");
while (fgets(input, sizeof(input), stdin) == NULL)
{
printf("Enter command \n");
} /*end whileloop*/
for (argumentsnum = 0; argumentsnum < 31; argumentsnum++)
{
temp = strtok(input, " \t\n");
if (temp != NULL)
{
arguments[argumentsnum] = temp;
} /*endif*/
} /*end forloop*/
if (strcmp(arguments[0], "exit") == 0)
{
printf("Exiting shell\n");
int i;
For(i=0;i<processes_count;i++){
exit(0);
}
} /*endif*/
pid_t id = fork();
processes_count++;
if (id == -1)
{
perror("Grab your own fork :@ \n");
exit(1);
} /*endif*/
else if (id == 0)
{
execvp(arguments[0], arguments);
} /*endelse*/
else
{
wait(&status);
}
} /*end while(1)*/
} /*endmain*/
最佳答案
execvp(arguments[0], arguments);
如果此调用失败,您需要执行某些操作。如果 execvp 由于传递了错误的命令而失败,则子进程将继续前进。这意味着子将处理下一个命令,而不是父。父进程将停留在其 wait()
调用中,等待子进程终止。
execvp(arguments[0], arguments);
perror("execvp");
_Exit(1);
关于c - c 中的 exit(0) 仅偶尔有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21356795/