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.