[英]Execution of a function form child process after receiving a SIGUSR1 signal
[英]Child process still does not run after receiving signal
該代碼是對此問題的答案之一。
#include<stdio.h>
#include<unistd.h>
#include<signal.h>
void
sigusr1( int pidno )
{
fprintf(stderr, "Caught\n");
}
int
main()
{
pid_t pid;
signal( SIGINT, sigusr1 );
if( (pid = fork()) == 0 ){
pause();
fprintf(stderr, "Child\n");
}
else
{
fprintf(stderr, "Parent\n");
kill( pid , SIGINT ); //parent sends signal to child
}
pause();
return 0;
}
子進程等待信號,並在接收到信號后繼續執行。
運行它我得到
Parent
Caught
似乎孩子在收到信號后沒有跑動。 按Ctrl + c:
Parent
Caught
^CCaught
Caught
Child
有人可以解釋一下這里發生了什么嗎?
子級收到並處理信號后 ,將調用pause()。 不幸的是, pause()容易引入這種競爭條件 :
time you parent child
---- --- ------ -----
0 signal(SIGINT,handler)
1 fork() (hello)
2 print("Parent") (waking up)
3 kill(..., SIGINT) <<SIGINT>> # RACE kill v pause
4 handler: print("Caught")
5 pause() pause()
6 ^C <<SIGINT>> <<SIGINT>>
7 handler: print("Caught") handler: print("Caught")
8 exit pause()
9 (still running)
要檢查到底發生了什么,請嘗試將%i,getpid()添加到printfs,還可能在子分支中的pause()調用之前再添加一個printf()。
sigsuspend()和顯式信號屏蔽可能是一個更好的選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.