UNIX环境高级编程学习之第十章信号-用信号实现父子进程同步时间:2021-03-17 04:42:58UNIX环境高级编程学习之第十章信号-用信号实现父子进程同步 /* FileName:ParentAndChildProcessSynchronous.c Date: 20100309 Description: 用信号实现父子进程同步。*/#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <signal.h>static volatile sig_atomic_t sigflag;static sigset_t newmask, oldmask, zeromask;static void sig_usr(int signo){ sigflag = 1;}void TELL_WAIT(void){ if (signal(SIGUSR1, sig_usr) == SIG_ERR) { printf("signal(SIGUSR1) ERROR /n"); exit(-1); } if (signal(SIGUSR2, sig_usr) == SIG_ERR) { printf("signal(SIGUSR2) ERROR /n"); exit(-1); } sigemptyset(&zeromask); sigemptyset(&newmask); sigaddset(&newmask, SIGUSR1); sigaddset(&newmask, SIGUSR2); if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0) { printf("SIB_BLOCK ERROR /n"); exit(-1); }} void TELL_PARENT(pid_t pid){ kill(pid, SIGUSR2);}void WAIT_PARENT(void){ while (sigflag == 0) { sigsuspend(&zeromask); } sigflag = 0; if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0) { printf("SIG_SETMASK ERROR/n"); exit(-1); }}void TELL_CHILD(pid_t pid){ kill(pid, SIGUSR1);}void WAIT_CHILD(void){ while (sigflag == 0) { sigsuspend(&zeromask); } sigflag = 0; if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0) { printf("SIG_SETMASK ERROR/n"); exit(-1); }}static void charatatime(char* );int main(int argc, char* argv[]){ pid_t pid; TELL_WAIT(); if ((pid = fork()) < 0) { printf("fork error/n"); exit(-1); }else if (pid == 0){ WAIT_PARENT(); charatatime("output from child/n"); }else{ charatatime("output from parent/n"); TELL_CHILD(pid); } return 0;}static void charatatime(char* str){ char* ptr; int c; setbuf(stdout, NULL); for (ptr = str; (c = *ptr++) != 0;) // 无缓冲的标准输出 { putc(c, stdout); }}