Skip to content
Advertisement

Part of the code in the child process spawned by fork() is skipped

I use fork() to spawn a child process to run some code, but I found that in the child process, some code like printf("child is running"); below will not run, and when I remove the sentences in switch(), it will run rightly, I can’t understand why this will happen.

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 Commandn");
                break;
        }
}

Advertisement

Answer

Like I said in the comment, change your printf line to

printf("child is runningn");

When you don’t use n at the end of the format string, printf usually doesn’t flush stdout straight away and so it may seem as if nothing has been executed.

If you don’t want to print the newline (for whatever reason), you could also flush stdout yourself:

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

I see no other reason as to why it appears not to be running. Also don’t forget to check if fork() returns -1, perhaps your user account has reached the limit of forked processes.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement