You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言OS进程程序执行到return 0仍无法终止问题求助

问题分析与解决方案

核心问题

  1. 输入0时父进程未退出循环:输入0后仅子进程跳出while循环,父进程仍留在循环内执行scanf等待输入,导致程序卡住无法退出。
  2. 子进程未主动终止:子进程break后会继续执行父进程的后续代码(如打印退出信息),造成冗余执行。
  3. 父进程等待子进程逻辑错误:while(wait(NULL) != -1)会持续等待所有已终止的子进程(包括历史僵尸进程),而非当前fork出的特定子进程,逻辑冗余。

修正后的代码

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main(){
    pid_t pid;
    int input;

    printf("Menu: \n 1 -> ls\n 2 -> ps\n 3 -> date\n 0 -> exit program\n");

    while (1) {
        printf("Enter: ");
        // 处理非数字输入导致的死循环问题
        if (scanf("%d", &input) != 1) {
            while (getchar() != '\n');
            printf("Invalid input, please enter a number.\n");
            continue;
        }

        if (input == 0) {
            // 输入0时直接终止父进程循环,无需创建子进程
            break;
        }

        pid = fork();
        if (pid == 0){
            if (input == 1){
                execlp("ls", "ls", NULL);
            }
            else if (input == 2){
                execlp("ps", "ps", NULL);
            }
            else if (input == 3){
                execlp("date", "date", NULL);
            }
            else{
                printf("Wrong Input\n");
            }
            // 子进程执行完成后强制退出,避免执行父进程后续代码
            exit(EXIT_FAILURE);
        }
        else if (pid > 0){
            // 父进程仅等待当前创建的子进程终止
            waitpid(pid, NULL, 0);
        }
        else {
            fprintf(stderr, "Fork Failed\n");
            exit(EXIT_FAILURE);
        }
    }
    printf("parent terminating\n");
    return 0;
}

关键修改说明

  • 输入0时直接终止父进程循环:无需创建子进程,直接进入退出逻辑,避免父进程继续等待输入。
  • 使用waitpid替代循环wait:精准等待当前fork出的子进程,避免无关的等待逻辑。
  • 子进程执行后强制退出:通过exit确保子进程不会执行父进程的后续代码,消除冗余执行。
  • 增加输入有效性校验:处理非数字输入导致的scanf死循环问题,提升程序鲁棒性。
  • 替换execvp为execlp:无需维护argv数组,直接传入命令参数,代码更简洁安全。

内容的提问来源于stack exchange,提问作者user16835652

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 11:53:15