- 论坛徽章:
- 0
|
回复 #7 JohnBull 的帖子
谢谢版主提示, 我对上面的程序做了修改,大致能运行正确了, 父子进程互相传递信号, 交替打印
- #include <stdio.h>
- #include <string.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <signal.h>
- #include <sys/uio.h>
- #include <sys/wait.h>
- #include <sys/errno.h>
- #define MAXCNT 4
- volatile sig_atomic_t contflag; /* set nonzero by signal handler */
- void sig_usr(int signo)
- {
- if( signo == SIGCONT) {
- contflag = 1;
- printf("received SIGCONT\n");
- } else
- printf("received unexpected signal(%d)\n", signo);
- return;
- }
- int main(void)
- {
- int idx = 0;
- int status;
- pid_t pid;
- sigset_t newmask;
- sigset_t oldmask;
- sigset_t zeromask;
- sigemptyset(&zeromask);
- sigemptyset(&newmask);
- sigaddset(&newmask, SIGCONT);
- if( (pid=fork()) < 0 ) {
- printf("fork error\n");
- exit(1);
- }else if (pid == 0) { /* child */
- while( idx < MAXCNT ) {
- if( signal(SIGCONT, sig_usr) == SIG_ERR ) {
- printf("c signal error\n");
- exit(2);
- }
- if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0) {
- printf("SIG_BLOCK error\n");
- exit(1);
- }
- printf("child[%d]\n", idx);
- printf("child pause ...\n");
- kill(getppid(), SIGCONT);
- while( contflag == 0)
- sigsuspend(&zeromask);
- printf("child up ...\n");
- contflag = 0;
- if( sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0 ) {
- printf("SIG_SETMASK error\n");
- exit(2);
- }
- idx++;
- }
- kill(getppid(), SIGCONT); /* child done */
- exit(99);
- }else { /* parent */
- while( idx < MAXCNT ) {
- if( signal(SIGCONT, sig_usr) == SIG_ERR ) {
- printf("p signal error\n");
- exit(3);
- }
- if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0) {
- printf("SIG_BLOCK error\n");
- exit(3);
- }
- printf("parent pause ...[%d]\n", idx);
- kill(pid, SIGCONT);
- while( contflag == 0)
- sigsuspend(&zeromask);
- printf("parent up ...\n");
- contflag = 0;
- if( sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0 ) {
- printf("SIG_SETMASK error\n");
- exit(3);
- }
- idx++;
- }
- if( waitpid(pid, &status, 0) < 0 ) {
- printf("waitpid error\n");
- exit(3);
- }
- }
- return 0;
- }
复制代码 |
|