gpt4 book ai didi

c - c 中的 exit(0) 仅偶尔起作用

转载 作者:太空宇宙 更新时间:2023-11-04 02:51:46 25 4
gpt4 key购买 nike

我正在尝试实现我自己的 shell,其中有很多东西无法正常工作,但现在我正在尝试解决第一个错误。当我的 shell 正在运行并且我输入 exit 作为第一个命令时,它工作正常,但是,当我输入 exit 作为第二个输入时,如果我将它作为第三个命令输入,我应该额外写 exit 以退出我的 shell ,我必须额外输入 2 次,依此类推。这是我的代码。

#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 失败是因为你向它传递了一个错误的命令,子进程将继续前进。这意味着 child 将处理下一个命令,而不是 parent。父项将停留在其 wait() 调用中,等待子项终止。

execvp(arguments[0], arguments);
perror("execvp");
_Exit(1);

关于c - c 中的 exit(0) 仅偶尔起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21356795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com