///
//这个例子是为了说明信号排队以及递送顺序
//关于信号的详细信息你可以参看man 7 signal
//本例采用的是POSIX实时信号的拓展信号:所有在SIGRTMIN和SIGRTMAX之间的信号都是实时信号,
//但是具体的数目并不是POSXI指定的
//为了解决一些POSIX信号模型的不足,特别是信号不能附带数据,以及多个信号可能会集中于一次递送的情况,POSIX实时信号的拓展就产生了。
//标准的POSIX信号模型有两个限制:当一个信号等待时,重新发送这个信号不会形成多次信号递送;
// 也没有多多个不同信号的递送顺序的保证。
//实时信号总是排成队列的;向应用程序发送的每一个信号都会被递送到这个程序(除非该程序已终止)。
//实时信号的顺序:代码较小的那些排在代码较大的信号之前递送。相同代码按照发送顺序递送。
//非实时信号之间没有定义顺序,实时信号和非实时信号之间也没有定义顺序。
/
//get the definition of strsignal( ) from string.h
#define _GUN_SOURCE 1
#include "head.h"
#include <sys/signal.h>
//globals for building a list of caught signals
int nextSig=0;
int sigOrder[ 10 ];
//catch a signal and record that is was handled
void handler( int signo )
{
sigOrder[ nextSig++ ]=signo;
}
int main( )
{
sigset_t mask;
sigset_t oldMask;
struct sigaction act;
int i;
//signals we're handling in this program
sigemptyset( &mask ); //inilializes the signal set given by set to empty
sigaddset( &mask,SIGRTMIN ); //add respectively signal signum to set
sigaddset( &mask,SIGRTMIN+1 );
sigaddset( &mask,SIGUSR1 );
//send signals to handler( ) and keep all signals blocked
//that handler( ) has been configured to catch to avoid
//races in manipulating the global variables
act.sa_handler=handler;
act.sa_mask=mask;
act.sa_flags=0;
sigaction( SIGRTMIN,&act,NULL );//examine and change a signal action
sigaction( SIGRTMIN+1,&act,NULL );
sigaction( SIGUSR1,&act,NULL );
//block the signals we're working with so we can see the queuing
//and ordering behavior
//sigprocmask() is used to fetch and/or change the signal mask of the calling thread
sigprocmask( SIG_BLOCK,&mask,&oldMask );
//generate signals
raise( SIGRTMIN+1 );//raise() sends a signal to the calling thread
raise( SIGRTMIN );
raise( SIGRTMIN);
raise( SIGRTMIN+1 );
raise( SIGRTMIN );
raise( SIGUSR1 );
raise( SIGUSR1 );
//enable delivery of the signals. they'll all be delivered right before this
//call returns( on linux;this is not portable behavior )
sigprocmask( SIG_SETMASK,&oldMask,NULL );
//display the ordered list signal we caught
//strsignal() returns a string describing the signal number which is the arguments
printf( "signals received:/n" );
for( i=0;i<nextSig;i++ )
{
if( sigOrder[ i ]<SIGRTMIN )
printf( "/t%s/n",strsignal( sigOrder[ i ] ) );
else
printf( "/tSIGRTMIN+%d/n",sigOrder[ i ]-SIGRTMIN);
}
return 0;
}
结果为:
winlin@winlin-Satellite:~/Mypro/Myc/ladsh$ ./queued
signals received:
User defined signal 1
SIGRTMIN+0
SIGRTMIN+0
SIGRTMIN+0
SIGRTMIN+1
SIGRTMIN+1
Linux实时信号举例
最新推荐文章于 2024-08-19 09:52:14 发布