c - c 中的 exit(0) 仅偶尔有效

标签 c shell loops exit

我正在尝试实现我自己的 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/

相关文章:

c - 我想打印一个元素在 C 中的随机数数组中重复的次数

c - 为什么下面的代码不打印整数的二进制表示形式?

bash - 为什么我的 `find` 命令给出与忽略目录相关的错误?

linux - 相对于其他 shell 命令,排序命令是否看到数据流乱序?

java - 在循环之前放入一条语句

r - 在 R 中不使用 for 的先前值的循环计算

C - 使用 while 和 switch/case 的菜单程序返回具有无效选择的重复菜单

C - 图形,无法旋转多边形

linux - 移动 30 分钟前的文件

python - 迭代两个列表并返回索引