Posted on 2009-01-04 20:04
Prayer 閱讀(432)
評論(0) 編輯 收藏 引用 所屬分類:
LINUX/UNIX/AIX
/*編制一段程序,使用系統調用fork()創建兩個子進程,
再用系統調用signal()讓父進程捕捉鍵盤上來的中斷信號(即按Del鍵),
當捕捉到中斷信號后,父進程用系統調用kill()向兩個子進程發出信號,
子進程捕捉到信號后,分別輸出下列信息后終止:
child process 1 is killed by parent!
child process 2 is killed by parent!
父進程等待兩個子進程終止后,輸出以下信息后終止:
parent process is killed !
*/
#include<stdio.h>
#include<signal.h>
#include<unistd.h>
void waiting();
void stop();
int wait_mark;
main()
{
int p1=-1, p2=-1;
//signal(SIGINT, stop); // position A
while ((p1 = fork()) == -1);
if (p1>0)
{ /*parent*/
while ((p2 = fork()) == -1);
if (p2>0)
{ /*parent*/
wait_mark=1;
signal(SIGINT, stop);// position B
waiting();
kill(p1,16); //*send signal 16 to end the process p1
kill(p2,17); //*send signal 17 to end the process p2
wait(0); //*waiting for the ending of p1
wait(0); //*waiting for the ending of p2
printf("parent process is killed!\n");
exit(0); //*quit from the parent process
}
else //*p2 work
{ /*child p2*/
wait_mark=1;
signal(17, stop);
waiting();
lockf(1,1,0);
printf("child process 2 is killed by parent!\n");
lockf(1,0,0);
exit(0); //* p2 quit
}
}
else //*p1 work
{ /*child p1*/
wait_mark=1;
signal(16, stop);
waiting();
lockf(1,1,0);
printf("child process 1 is killed by parent!\n");
lockf(1,0,0);
exit(0); //* p1 quit
}
}
void waiting( )
{
while (wait_mark != 0);
}
void stop()
{
wait_mark=0;
}
又研究了一下,在兩個子進程開始就加入signal(SIGINT,SIG_IGN),就滿足要求了。看來原來的Ctrl-c信號對所有進程都起作用了,所以得把它給禁了,才能合要求。