- #include <signal.h>
- #include <stdio.h>
- #include <iostream.h>
- #filename: 1. C
- static void sig_usr(int);
- int main(void)
- {
- cout<<"SIGUSR1:"<<SIGUSR1<<endl;
- if(signal(SIGUSR1,sig_usr) == SIG_ERR)
- cout<<"can't catch SIGUSR1 /n"<<endl;
- if(signal(SIGUSR2,sig_usr) == SIG_ERR)
- cout<<"can't catch SIGUSR2"<<endl;
- if(signal(SIGBUS,sig_usr) == SIG_ERR)
- cout<<"can't catch SIGBUS"<<endl;
- for(;;)
- pause();
- }
- static void sig_usr(int signo)
- {
- if(signo == SIGUSR1)
- cout<<"received SIGUSR1!"<<endl;
- else if(signo == SIGUSR2)
- cout<<"received SIGUSR2!"<<endl;
- else
- cout<<"received signal:"<<signo<<endl;
- return;
- }
編譯該程序: $:g++ -o test1 1.C
得到可執行文件test1,然後再後臺運行1
$: test1 &
[1] 5201
然後向進程5201觸發SIGUSR1信號:
$: kill -10 5201
$:received SIGUSR1!
並且SIGUSER2的值爲:12,通過kill -12 5201,可以觸發SIGUSER2信號。
爲了解決當觸發SIGUSER1信號誤觸發Accept,對於Accept的調用應該按照如下方式:
while(1)
{
int nRet = accept(....);
if ( nRet == -1 )
{
if (errno == EINTR)
continue;
else
return ;
}
/* do something ..... */
}