- 论坛徽章:
- 0
|
目前学习到Unix信号,课后习题10.6主要利用书中的TELLWAIT,TELLPARENT,TELLCHILD,WAITPARENT,WAITCHILD处理父子进程交替输出。自己写了一段程序输出如下:
parent write 0
child write 0
parent write 1
然后程序一直阻塞。。。不知道什么问题,哪位高手帮助解决并解释一下。
程序如下:
static volatile sig_atomic_t sigflag = 0; /* set nonzero by sig handler */
static sigset_t newmask, oldmask, zeromask;
static void
sig_usr(int signo) /* one signal handler for SIGUSR1 and SIGUSR2 */
{
sigflag = 1;
}
void
TELL_WAIT(void)
{
if (signal(SIGUSR1, sig_usr) == SIG_ERR)
err_sys("signal(SIGUSR1) error");
if (signal(SIGUSR2, sig_usr) == SIG_ERR)
err_sys("signal(SIGUSR2) error");
sigemptyset(&zeromask);
sigemptyset(&newmask);
sigaddset(&newmask, SIGUSR1);
sigaddset(&newmask, SIGUSR2);
/*
* Block SIGUSR1 and SIGUSR2, and save current signal mask.
*/
if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0)
err_sys("SIG_BLOCK error");
}
void
TELL_PARENT(pid_t pid)
{
kill(pid, SIGUSR2); /* tell parent we're done */
}
void
WAIT_PARENT(void)
{
while (sigflag == 0)
{ sigsuspend(&zeromask);} /* and wait for parent */
sigflag = 0;
/*
* Reset signal mask to original value.
*/
if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
err_sys("SIG_SETMASK error");
}
void
TELL_CHILD(pid_t pid)
{
kill(pid, SIGUSR1); /* tell child we're done */
}
void
WAIT_CHILD(void)
{
while (sigflag == 0)
{sigsuspend(&zeromask);} /* and wait for child */
sigflag = 0;
/*
* Reset signal mask to original value.
*/
if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
err_sys("SIG_SETMASK error");
}
char byte[1] = {'0'};
int main()
{
pid_t pid,parent_pid,child_pid;
int fd;
parent_pid = getpid();
TELL_WAIT();
if((pid = fork()) < 0)
{
printf("fork error!\n");
}
else if(pid == 0)
{
while(1)
{
WAIT_PARENT();
printf("child write %c\n",byte[0]);
byte[0]++;
sleep(1);
TELL_PARENT(parent_pid);
}
}
else
{
while(1)
{
printf("parent write %c\n",byte[0]);
byte[0]++;
sleep(1);
TELL_CHILD(pid);
WAIT_CHILD();
}
}
exit(0);
}
|
|