Fork bug

Submitted by fork
on November 29, 2004 - 9:35am

Hello,

Here a program with a parent process that creates a child process. The fork must
return the pid of the child in the parent process. However, the child is scheduled before the parent gets the pid of its child. The program I tested is the following:

#include
#include
#include
#include

pid_t pid_fils=33;

void a() {
printf(" %d \n", pid_fils);
getchar();
}

int main(void) {
signal(SIGUSR1, a);
switch ((pid_fils=fork())) {
case -1: perror("fork"); exit(1);
case 0: kill(getppid(), SIGUSR1); exit(0);
default : pause();
}
return 0;
}

Is it a bug of the fork implementation ? Is there a patch for this ?

Thank you.

Re: Fork

Anonymous
on
November 29, 2004 - 10:48am

This is not a bug with fork. POSIX does not state the scheduling order of child and parent following a fork. Most implementations schedule the child first so that the child can properly initialize.

That being said, there is a race condition is the code. The race is between child sending usr1 and the parent executing pause.

You must block the signal first and then use sigsuspend.

pid_t pid_fils = 33;

void sigusr1(int signo) {
printf("%jd\n",(intmax_t)pid_fils);
getchar( );
}

int
main(int argc,char *argv[])
{
sigset_t sset;
sigset_t oset;

signal(SIGUSR1,sigusr1);

sigemptyset(&sset);
sigaddset(&sset,SIGUSR1);

sigprocmask(SIG_BLOCK,&sset,&oset);

switch((pid_fils = fork())) {
case -1 :
perror("fork"); exit(1);
case 0 :
kill(getppid(),SIGUSR1);
exit(0);
default:
sigsuspend(&oset);
}

return 0;
}

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.