ETL
ETL

Reputation: 43

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.

Upvotes: 2

Views: 323

Answers (4)

Majid Azimi
Majid Azimi

Reputation: 5745

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.

Upvotes: 0

kjp
kjp

Reputation: 3116

Try adding a fflush(stdout) after the printfs.

Upvotes: 0

Michael Burr
Michael Burr

Reputation: 340218

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.

Upvotes: 3

patapizza
patapizza

Reputation: 2398

Maybe you don't let enough time for the child. Try to add a waitpid() call in the parent code.

Upvotes: 0

Related Questions