segmentation fault 뜨는 이유를 모르겠습니다...

쇼난@Naver의 이미지

도저히 못찾겠습니다.
프로세스 3개를 번갈아 실행(파일 열어 카운트)하는 코드입니다.
자식1->자식2->부모->자식1->....

왜인지 모르겠는데 항상 13000~14000쯤에서 세그멘테이션 폴트가 뜹니다..
코드입니다.

#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
 
char *filename;
int num;
sigset_t mask, unmask;
 
struct pid_s {
	pid_t cur;
	pid_t next;
}pid_struct;
 
 
void sig_wake(int signo)
{
 
	//LOCK
	sigprocmask(SIG_BLOCK, &mask, &unmask);
 
	//COUNT
	int cnt;
	char numstr[100];
  	int fp = open(filename, O_RDONLY|O_SYNC);
	lockf(fp,F_LOCK, 10L);
	read(fp, numstr, 100);
	cnt = atoi(numstr);
	close(fp);	
	cnt++;
	fp = open(filename, O_RDWR|O_SYNC|O_TRUNC,0644);
	lockf(fp,F_LOCK, 10L);
	sprintf(numstr, "%d",cnt);
	write(fp, numstr, 10L);
	close(fp);
	printf("process[%d] count %d target %d\n", getpid(), cnt, num);	
 
	//Kill to next process
	if(cnt < num){
		kill(pid_struct.next, SIGUSR1);
	}
 
	//UNLOCK
	sigsuspend(&unmask);
 
 
}
 
void sig_sleep(int signo){
	pause();
}
 
void sig_quit(int signo)
{
}
 
int main(int argc, char *argv[])
{
	pid_t child[3];
	int fd;
	int count, i, pidx;
	num = atoi(argv[1]);
 
	filename = argv[2]; 
 
	struct sigaction pwake, psleep, pquit;
 
	pwake.sa_handler = sig_wake;
	psleep.sa_handler = sig_sleep;
	pquit.sa_handler = sig_quit;
 
	sigaction(SIGUSR1, &pwake, NULL);
	sigaction(SIGUSR2, &psleep, NULL);
	sigaction(SIGQUIT, &pquit, NULL);
 
	sigfillset(&mask);
	sigfillset(&unmask);
	sigdelset(&unmask, SIGUSR1);
	sigdelset(&unmask, SIGUSR2);
	sigdelset(&unmask, SIGQUIT);
 
	//FILE OPEN	
 
	//Test 1 : Check that an integer greater than 0
	if(num <= 0){
		printf("Wrong Input Number\n");
		return -1;	
	}
 
	//Test 2 : Does the file exist
	fd = open(filename, O_RDWR|O_CREAT|O_TRUNC,0644);
	write(fd,"0", 4);
	close(fd);
 
	for(i=1; i>=0; i--) {
		child[i] = fork();
		if(child[i] == 0)               
			break;
	}
 
	if (i == 1){
		printf("in here\n");
		pid_struct.next = getppid();
		pid_struct.cur = getpid();
		kill(pid_struct.next, SIGUSR1);
		pause();
	}
	else{
		pid_struct.next = child[i+1];
		pid_struct.cur = getpid();
		pause();
	}
 
 
 
 
 
	return 0;
}
chocokeki의 이미지

write(fd,"0", 4);
이래도 되나요?

m4170의 이미지

strace -ff 옵션을 주고 한번 프로세스가 어떤 위치에서 시그널을 받는지 확인해 보시는 것은 어떠신가요?
(실행예 : strace -ff ./a.out)