fork()生成的子进程中的部分代码被跳过

问题描述 投票:-1回答:1

我使用fork()生成一个子进程来运行一些代码,但是我发现在子进程中,下面的printf("child is running");等代码将无法运行,当我删除switch()中的句子时,它会正常运行,我无法理解为什么会这样。

pid_t pid = fork();
if(pid == 0){
        int execl_status = -1;
        printf("child is running");  // this will not run

        switch(cmdIndex)
        {
            case CMD_1:
                execl_status = execl("./cmd1","cmd1",NULL);
                break;
            case CMD_2:
                execl_status = execl("./cmd2","cmd2",NULL);
                break;
            case CMD_3:
                execl_status = execl("./cmd3","cmd3",NULL);
                break;
            default:
                printf("Invalid Command\n");
                break;
        }
}
c linux operating-system
1个回答
1
投票

就像我在评论中所说,将你的printf线改为

printf("child is running\n");

当你不在格式字符串的末尾使用\n时,printf通常不会立即冲洗stdout,所以看起来似乎没有执行任何操作。

如果您不想打印换行符(无论出于何种原因),您也可以自己刷新stdout

printf("child is running");
fflush(stdout);

我没有看到为什么它似乎没有运行的其他原因。另外不要忘记检查fork()是否返回-1,也许您的用户帐户已达到分叉进程的限制。

© www.soinside.com 2019 - 2024. All rights reserved.