signal_rt.c

来自「这个是专门针对实时信号做的代码 用到了各个实时信号涉及到的函数 同时对实时信」· C语言 代码 · 共 73 行

C
73 行
字号
#include <sys/types.h>

#include <unistd.h>

#include <signal.h>

#include <stdio.h>

#include <stdlib.h>



static void sig_rt(int, siginfo_t *, void * ) ;

static int signal_rt(int, void *);



int main(int argc, char **argv)

{

	int i, j;

	pid_t pid;

	sigset_t newset;

	union sigval val;

	printf("SIGRTMIN = %d, SIGRTMAX = %d\n", (int) SIGRTMIN, (int) SIGRTMAX);

	if ( (pid = fork() ) == 0) {

	// child: block three realtime signals 

	sigemptyset(&newset);

	sigaddset(&newset, SIGRTMAX);

	sigaddset(&newset, SIGRTMAX - 1);

	sigaddset(&newset, SIGRTMAX - 2);

	sigprocmask(SIG_BLOCK, &newset,NULL);

		

	// establish signal handler with SA_SIGINFO set 

	

	signal_rt(SIGRTMAX, sig_rt);

	signal_rt(SIGRTMAX - 1, sig_rt);

	signal_rt(SIGRTMAX - 2, sig_rt);

	

	sleep(6) ; // let parent send all the signals 

	sigprocmask(SIG_UNBLOCK, &newset, NULL); //unblock 

	sleep (3 ) ; // let all queued signals be delivered 

	exit (0) ;

	}

// parent sends nine signals to child 

	sleep(3) ; // let child block all signals 

	for (i = SIGRTMAX; i >= SIGRTMAX - 2; i--) 

	{for (j = 0; j <= 2; j++) {

		val.sival_int = j;

		sigqueue (pid, i, val) ;

		printf("sent signal %d, val = %d\n", i, j);

		}

	}

exit (0) ;

}



 static void sig_rt(int signo, siginfo_t *info, void *context)

 {

 printf("received signal #%d, code = %d, ival = %d\n",signo, info->si_code, info->si_value.sival_int);

 }

 



 static int signal_rt(int signo, void *func)

{

 struct sigaction act, oact;

 act.sa_sigaction = func; //must store function addr here 

 sigemptyset(&act.sa_mask);

 act.sa_flags = SA_SIGINFO; // must specify this for realtime 

 if (signo == SIGALRM) {

 #ifdef SA_INTERRUPT

 act.sa_flags |= SA_INTERRUPT; // SunOS 4.x 

 #endif

 }else{

 #ifdef SA_RESTART

 act.sa_flags |= SA_RESTART; // SVR4, 4.4BSD 

 #endif

 }

 if (sigaction(signo, &act, &oact) < 0)

 		{perror("sigaction error");return(-1);}

 return (1);

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?