父子进程通过sigaction实现数数问题

m0_38069510 2018-07-03 08:02:40
问题是通过SIGUSR1和SIGUSR2实现父子进程的交替数数
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <signal.h>
#include <sys/time.h>
#include <pthread.h>
#include <semaphore.h>
int num=1;
int flag;
void father(int signo)
{
printf("father process:num[%d]\n",num);
num+=2;;
flag=0;
sleep(1);
}
void son(int signo)
{
printf("child process:num[%d]\n",num);
num+=2;
flag=0;
sleep(1);

}
void sigint(int signo)
{

}
int main(int argc,char *argv[])
{
int pid;
if((pid=fork())<0)
{
perror("fork");
return -1;
}
if(pid>0)
{
num=0;
flag=1;
struct sigaction act;
act.sa_flags=0;
act.sa_handler=father;
sigaddset(&act.sa_mask,SIGUSR1);//已经设置阻塞信号集了,当SIGUSR1被触发的时候,会被阻塞,可运行为什么不会阻塞。
//sigprocmask(SIG_BLOCK,&act.sa_mask,NULL);//加上这句话就会阻塞,为什么?
sigaction(SIGUSR1,&act,NULL);
//signal(SIGUSR1,father);
//signal(SIGINT,sigint);
while(1)
{
if(flag==0)
{
kill(pid,SIGUSR2);
flag=1;
}
}
}
if(pid==0)
{
num=1;
flag=0;
struct sigaction act;
act.sa_flags=0;
act.sa_handler=son;
sigaddset(&act.sa_mask,SIGUSR2);
//sigprocmask(SIG_BLOCK,&act.sa_mask,NULL);
sigaction(SIGUSR2,&act,NULL);
//signal(SIGUSR2,son);
//signal(SIGINT,sigint);
while(1)
{
if(flag==0)
{
kill(getppid(),SIGUSR1);
flag=1;
}
}
}
return 0;
}
...全文
210 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
宁南学者 2018-07-04
  • 打赏
  • 举报
回复
sigprocmask 是设置对信号进行阻塞的。
宁南学者 2018-07-04
  • 打赏
  • 举报
回复
sigaddset仅仅将USER信号添加到那个set集合,并没有设置 -阻塞。

18,777

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 专题技术讨论区
社区管理员
  • 专题技术讨论区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧