Kshine0 2011-03-11
////////////////////////////////////////////////////
//本例是一个用信号发送数据元素的例子
//可以使用 man sigqueue 获得更多信息
//siginfo_t结构允许发送的信号带有一个单独的数据(这个元素可以是一个指针,从而间接传递任意大小的数据 ),要用 union sigval
//sigqueue()可以传送带有数据的消息到指定的进程。要生成一个带有union sigval的信号,必须使用sigqueue()
//要接收union signal,捕捉信号的进程必须在通过sigaction()注册它的信号处理程序时使用SA_SIGINFO
///////////////////////////////////////////////////
#include "head.h"
#include <sys/signal.h>
//catch a signal and record that it was handled
void handler( int signo,siginfo_t* si,void * context )
{
printf( "%d\n",si->si_value.sival_int );
}
int main( )
{
sigset_t mask;
sigset_t oldMask;
struct sigaction act;
int me=getpid( );
union sigval val;
//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_sigaction=handler;
act.sa_mask=mask;
act.sa_flags=SA_SIGINFO;
sigaction( SIGRTMIN,&act,NULL );
//block the signals we're working with so we can see the queuing
sigemptyset( &mask );
sigaddset( &mask,SIGRTMIN );
//the "mask" value of the signal mask is stored in "oldMask".
sigprocmask( SIG_BLOCK,&mask,&oldMask );
//genertae signals
val.sival_int=1;
sigqueue( me,SIGRTMIN,val );
val.sival_int++;
sigqueue( me,SIGRTMIN,val );
val.sival_int++;
sigqueue( me,SIGRTMIN,val );
//enable delivery of the signals
sigprocmask( SIG_SETMASK,&oldMask,NULL ); //don't save the oldMsk
return 0;
}
结果:
1
2
3
union sigval {
int sival_int;
void *sival_ptr;
};
siginfo_t {
int si_signo; /* Signal number */
int si_errno; /* An errno value */
int si_code; /* Signal code */
int si_trapno; /* Trap number that caused
hardware-generated signal
(unused on most architectures) */
pid_t si_pid; /* Sending process ID */
uid_t si_uid; /* Real user ID of sending process */
int si_status; /* Exit value or signal */
clock_t si_utime; /* User time consumed */
clock_t si_stime; /* System time consumed */
sigval_t si_value; /* Signal value */
int si_int; /* POSIX.1b signal */
void *si_ptr; /* POSIX.1b signal */
int si_overrun; /* Timer overrun count; POSIX.1b timers */
int si_timerid; /* Timer ID; POSIX.1b timers */
void *si_addr; /* Memory location which caused fault */
int si_band; /* Band event */
int si_fd; /* File descriptor */
}