SIGCHLD and watpid()

I am launching a number of processes using fork(), of which only a particular process i need to catch in parent process, others would be caught in signal handler, in which a wait() is waiting for any process. My question is the signal handlers wait() and waitpid() would cause some sort of race condition ?? Or the result is that signal handlers wait will return always -1 for that particular pid for which waitpid() is waiting for ?? For the sample example below, i always get -1 from the wait() but is it always so ?? Thanx in advance.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>

void sigChld(int arg){
	int pid ;
	printf("SIGCHLD caught\n") ;
	pid = wait(NULL) ;
	printf("signal's wait() caught pid %d\n", pid) ;
	signal(SIGCHLD, sigChld) ;
}

int main(){
	signal(SIGCHLD, sigChld) ;
	int pid ;
	pid = fork() ;
	if (pid == 0){
		int status = getpid() ;
		printf("child pid is %d\n", status) ;
		for (int i = 0, j = 0 ; i < 1000000 ; i++, j++) ;
		printf("child is gonna return %d\n", status) ;
		exit(NULL) ;
	}else{
		printf("Waiting for pid %d\n", pid) ;
		int ret ;
		int x = waitpid(pid, &ret, 0) ;
		printf("wait pid returns %d\n" , x) ;
	}
			
}


Waiting for pid 7179
child pid is 7179
child is gonna return 7179
SIGCHLD caught
signal's wait() caught pid -1
wait pid returns 7179
Check errno after wait() to see why you got -1.
Topic archived. No new replies allowed.