fork和等待子进程似乎根本没有等待

时间:2015-05-10 08:03:55

标签: c linux shell

我们正在创建一个简单的shell进程。

这是代码:

pid = fork();

        if (pid == -1) {
            printf("fork error");

        }else if (pid > 0) {
            wait(&status);

        }

        else if (pid == 0) {
            execute(myarg);

        }

这是执行函数: void execute(int argc){

switch (argc) {

case 1:
    execlp(arg[0], arg[0], NULL);
case 2:
    execlp(arg[0], arg[0], arg[1], NULL);
case 3:
    execlp(arg[0], arg[0], arg[1], arg[2], arg[3], NULL);
case 4:
    execlp(arg[0], arg[0], arg[1], arg[2], arg[3], arg[4], NULL);
default:
    printf("Error in switch\n");
}

我的问题通常是如果我们遇到案例1~4,没有问题。但是如果我们遇到默认值,退出shell的硬代码只有在我输入相同数量的“错误在交换机”中时才能工作。帮帮我!!!

当我没有收到“开关错误”时的结果:

kevinshell>> ls  
myshellw.c  posix  posix.c  posix.c~  shell-l.c~  test  test.c`
kevinshell>> exit

以及出现错误的时候:

kevinshell>> stuff
Error in switch
kevinshell>> stuff
Error in switch
kevinshell>> another
Error in switch
kevinshell>> exit
kevinshell>> exit
kevinshell>> exit
kevinshell>> exit

1 个答案:

答案 0 :(得分:2)

在默认情况下,您必须在printf之后调用exit。否则你的孩子过程永远不会退出...

这适用于案例1-4的原因是exec *调用正在用所请求的程序替换当前过程映像,并最终该程序调用exit

来自man exec:

  

exec()函数系列替换当前的过程映像          一个新的过程图像。本手册页中描述的功能是          execve(2)的前端。 (参见execve(2)的手册页 -          关于更换当前过程映像的详细信息。)

如果你发布完整的代码,我将能够进一步解释孩子在printf行之后做了什么(我猜它再次分叉,因为普通的shell会在循环中运行这段代码)

相关问题