分类: C/C++
2010-11-01 18:14:42
/********
signal函数
*********/
#include
#include
#include
#include
void sig_handler(int sig)
{
switch(sig)
{
case 2:
printf("Reevied signal:SIGINT\n");
break;
case 3:
printf("Reevied signal:SIGQUIT\n");
break;
default:;
}
return;
}
int main()
{
printf("PID:%d\n",getpid());
signal(SIGINT,sig_handler);
signal(SIGQUIT,sig_handler);
for(;;);
return 0;
}
/************
sigaction函数
*************/
#include
#include
#include
#include
void sig_handler(int sig, siginfo_t *info, void *t)
{
printf(" Reevied signal:%d\n",sig);
return;
}
int main()
{
int status;
struct sigaction act;
act.sa_sigaction = sig_handler;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_SIGINFO;
status=sigaction(SIGINT,&act,NULL);
if(status<0)
{
printf("signaction error");
}
for(;;);
return 0;
}
/*************************************
**在不同进程间实现信号发送和接收send.c**
**************************************/
#include
#include
#include
#include
int main(int argc, char **argv)
{
int status;
pid_t pid;
union sigval sg;
if(argc!=2)
{
printf("arguments error:\n");
exit(1);
}
pid = atoi(argv[1]);
sg.sival_init=getpid();
status = sigqueue(pid,SIGUSR1,sg);
if(status<0)
printf("send error\n");
else
printf(Done\n);
return 0;
}
/************************************
**在不同进程间实现信号发送和接收receive.c*
*************************************/
#include
#include
#include
#include
void sig_handler(int sig, siginfo_t *info, void *t)
{
printf(" Reevied signal:%d\n",sig);
printf(" Reevied message:%d\n",info->si_int);
return;
}
int main()
{
int status;
pid_t pid;
pid = getpid();
struct sigaction act;
act.sa_sigaction = sig_handler;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_SIGINFO;
status=sigaction(SIGUSR1,&act,NULL);
if(status<0)
{
printf("signaction error");
}
printf("Recever:\n");
printf("PID:%d\n",pid);
for(;;);
return 0;
}
/************
**alarm定时**
*************/
#include
#include
int main()
{
int status, i;
i=0;
alarm(1);
while(1)
{
printf("i=%d:\n",i);
i++;
}
return 0;
}
/********
**信号集**
*********/
#include
#include
#include
#include
void sig_handler(int sig)
{
printf("Receive signal: SIGINT\n");
return;
}
int main()
{
sigset_t set;
sigemptyset(&set);
sigaddset(&set,SIGINT);
signal(SIGINT,sig_handler);
while(1)
{
sigprocmask(SIG_BLOCK,&set,NULL);
printf("SIGINT is blocked\n");
sleep(5);
sigprocmask(SIG_UNBLOCK,&set,NULL);
printf("SIGINT is unblocked\n");
sleep(5);
}
return 0;
}