c - 简单 C 子/父程序中的意外终止

标签 c signals fork kill

所以我一直在阅读 StackOverflow 和 fork 手册页上的帖子,但我只是看不到我看到的行为,可能是因为我只是在寻找我所期望的。

这是一个简单的程序,它获取一个文件名,产生一个 child ,在文件上运行 stat(),然后在循环中将 SIGUSR1 或 2 返回给父级。 parent 只想知道它是 1 还是 2 ... 我得到的是“用户定义的信号 2”,然后程序退出。但是父级处于 while 循环中,对吧?

无论如何,我真的希望有人能解释为什么我没有得到预期的输出,特别是循环不断地询问文件名并每次生成一个 child ,而 parent 知道 child 返回什么信号杀死()。

pid_t pid;

while(1) {
    if(pid == 0) // i am the child
    {
        FILE *fp = fopen(fname, "r");
        if(fp == NULL){
            printf("%d] Child cannot find [%s].", msg++, fname);
            fclose(fp);
        }
        else {
            stat(fname, &st);
            n = st.st_size;
            printf("%d] Child read %d chars.\n", msg++, n);
            if(n%2) kill(pid, SIGUSR1);
                else kill(pid, SIGUSR2);
        }

    }
    else // im the parent
    {
        if( signal(SIGUSR1,NULL) ) // Code never gets here because it ends
            printf("%s is odd\n", fname );

        if( signal(SIGUSR2, NULL) )
            printf("$s is even\n", fname );

        printf("%d] Enter filenames until you're happy. 'die' to end.\n", msg++);
        scanf("%s", fname);
        pid = fork();
    }

}
return 0;

最佳答案

在子进程中,pidfork 将子进程 pid 返回给父进程,但子进程得到了 ,而你试图杀死一个 pid 为 0 的进程,但 init 的 pid 是 1,你可以使用 getpid() 来获取当前的 pid child 。然后尝试向它发出信号。

编辑: 而且,pid 在循环第一次进入时未初始化,这也可能导致未定义的行为。谢谢@Giresh

关于c - 简单 C 子/父程序中的意外终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21449161/

相关文章:

c - 将字段中的位扩展到掩码中所有(重叠+相邻)设置位的最快方法?

c - 超线程的最佳 gcc 优化开关

c - fork - 父子程序

codeigniter - 在 github 上 fork CodeIgniter

c - unix 中的信号/警报问题

c - cd (C) 的 Minishell 问题

从 .h 文件调用函数

c - gcc 4.2.1 链接问题 : Undefined Symbols for Architecture x86_64

C fork 和进程,为什么有必要这样做?

c - POSIX 线程/信号 : Portable way to determine to which thread a signal was delivered?