关于Linux操作系统一些不懂的地方
如果按下面的代码,在Linux系统下运行,
在5秒内按下"ctrl + c"产生中断的结果是:
This is parent process, pid = 一个整数,
This is child process 1 pid = 一个整数,
This is child process 2 pid = 一个整数,
Parent process will be killed, The children will be killed first!
这个结果我知道...
----------------------------------------------------------------------------
现在我把函数parent_stop()中的 "exit(0);" 去掉,
然后也同样的运行时按下"ctrl + c"产生中断,
执行的结果是这样的:
This is parent process, pid = 一个整数,
This is child process 1 pid = 一个整数,
This is child process 2 pid = 一个整数,
Parent process will be killed, The children will be killed first!
Parent process (pid = 一个整数) finished! //比上面的结果多出来的
-----------------------------------------------------------------------------------
打印出来了这句:Parent process (pid = 一个整数) finished!
说明在执行parent_stop后,程序返回,执行下面语句
程序代码:
kill(pid1, SIGUSR1); kill(pid2, SIGUSR2); wait(0); wait(0); printf("Parent process (pid = %d) finished!\n", getpid()); exit(0);我不明白的是,为什么执行了
kill(pid1, SIGUSR1);
kill(pid2, SIGUSR2);
这两句,给两个子进程发送了SIGUSR1,SIGUSR2信号,
为什么子进程没有调用child_stop()函数,打印那两句话呢????子程序已经死掉了吗???
程序代码:
程序代码:
#include<signal.h> #include<unistd.h> #include<sys/types.h> void parent_stop(); void child_stop(); main() { int pid1, pid2; while((pid1 = fork()) == -1); if(pid1 > 0) { while((pid2 = fork()) == -1); if(pid2 > 0) { printf("This is parent process ,pid = %d\n", getpid()); signal(SIGINT, parent_stop); //按"ctrl + c"退出 signal(SIGQUIT, parent_stop); //按"ctrl + \"退出 sleep(5); kill(pid1, SIGUSR1); kill(pid2, SIGUSR2); wait(0); wait(0); printf("Parent process (pid = %d) finished!\n", getpid()); exit(0); } else { printf("This is child process 2 pid = %d\n", getpid()); signal(SIGUSR2, child_stop); sleep(6); } } else { printf("This is child process 1 pid = %d\n", getpid()); signal(SIGUSR1, child_stop); sleep(6); } } void parent_stop() { printf("Parent process will be killed, The children will be killed first! \n"); exit(0); //标记处 } void child_stop() { printf("Child process (pid = %d) be killed \n", getpid()); exit(0); }