C fork function strange behaviour on Unix (HP-UX)
I have the classic fork code on a C program as follows:
int status;
if((pid = fork()) < 0)
{
printf("SOME fork() ERROR...\n");
}
else if(pid == 0)
{
//Child stuff
printf("CHILD CODE\n");
}
else
{
//parent stuff
printf("PARENT 开发者_运维知识库CODE\n");
while (wait(&status) != pid);
}
It compiles OK, and I was running it to do some tests until something I don't understand happened: Suddenly in the terminal I only saw written "PARENT CODE". As I understand if the child process is not created "SOME fork() ERROR..." and "PARENT CODE" is what must be displayed on screen. (Is this true?) But only the last appears. My first thought was mmmm... the fork succeeded but.. the child doesn't execute it's code?????????? Is this even possible?
Thanks for you time and help.
Edit: the variable status and wait(...) are on the program, I only print messages to try the see what is happening in a simpler manner.
It's HP-UX 11
Thanks to all for your answers.
How is pid
declared?
Is it possible that it's an unsigned type (instead of using the type pid_t
which should be signed)? If that's the case, an error return from fork()
won't be detected as such.
Maybe you don't let enough time for the child. Try to add a waitpid()
call in the parent code.
Try adding a fflush(stdout)
after the printf
s.
There is something strange in the code: the child process doesn't exit.
else if(pid == 0)
{
//Child stuff
printf("CHILD CODE\n");
_exit(EXIT_SUCCESS);
}
Maybe this solves the problem.
精彩评论