注册 登录
编程论坛 Linux教室

关于Linux操作系统一些不懂的地方

kingzhui006 发布于 2009-09-25 12:55, 1663 次点击

如果按下面的代码,在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);
}
5 回复
#2
zhddragon2009-09-26 22:03
以下是引用kingzhui006在2009-9-25 12:55:32的发言:


我不明白的是,为什么执行了
kill(pid1, SIGUSR1);
kill(pid2, SIGUSR2);
这两句,给两个子进程发送了SIGUSR1,SIGUSR2信号,
为什么子进程没有调用child_stop()函数,打印那两句话呢????子程序已经死掉了吗???
因为SIGUSR1和SIGUSR2这两个信号的默认动作是终止进程,而你在程序中并没有调用signal或sigaction捕获这两个信号。
#3
kingzhui0062009-09-28 08:07
在两个子程序中不是有 signal(SIGUSR2, child_stop);
用来捕获父进程的信号吗
没听懂.
#4
zhddragon2009-09-29 00:25
回复 3楼 kingzhui006
不好意思,刚开始没有留意到那两个signal函数。

shell中ctrl+c和ctrl+\会把信号发送给前台进程组的每一个进程,所以子进程也收到了这个信号,于是就直接退出了。如果你要测试的话直接用在shell中用kill给父进程发SIGINT或SIGQUIT信号就好了。
#5
flyingcloude2009-10-01 13:07
这个版块很冷清啊
#6
cneagle2009-10-12 16:25
都去WINdows了
1