1. 程式人生 > >linux使用訊號傳遞訊息的說明與用法

linux使用訊號傳遞訊息的說明與用法

下面是傳送訊號端的程式碼:

#define _GNU_SOURCE
#include <signal.h>
#include <string.h>
#include <setjmp.h>
#include "signal_functions.h"
#include "tlpi_hdr.h"


int main(int argc,char* argv[])
{
	int sig,numSigs,j,sigData;
	
	union sigval sv;
	
	if(argc<4||strcmp(argv[1],"--help") ==0)
		usageErr("%s pid sig-num data [num-sigs]\n", argv[0]);
	
	printf("%s: PID is %ld, UID is %ld\n", argv[0],
        (long) getpid(), (long) getuid());
	
	sig = getInt(argv[2],0,"sig-num");
	sigData=getInt(argv[3],GN_ANY_BASE,"data");
	numSigs = (argc>4)?getInt(argv[4],GN_GT_0,"num-s"):1;
	
	for(j=0;j<numSigs;j++)
	{
		sleep(1);
		sv.sival_int = sigData+j;
		if(sigqueue(getLong(argv[1],0,"pid"),sig,sv)== -1)
			errExit("sigqueue %d",j);
	}
	
	exit(EXIT_SUCCESS);
}
	

下面是接收訊號端的程式碼:

#define _GNU_SOURCE
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

static void
handler(int signum,siginfo_t *sv,void *myact) 
{ 
	printf("receive signal %d\n", signum); 
	printf("signal value is %d\n",sv->si_value.sival_int);
} 

int main(int argc,char* argv[])
{
	struct sigaction sa;
	
	sa.sa_handler=handler;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = SA_SIGINFO;           /* Handler uses alternate stack */
    if (sigaction(SIGINT, &sa, NULL) == -1)
	{
		perror("sigaction\n");
		exit(1);
	}
       
	while(1)
	{
		sleep(1);
	}
	exit(EXIT_SUCCESS);
}