c - 退出程序会不会自动关闭管道?

标签 c process pipe kill waitpid

假设我在子进程和父进程之间创建一个管道,子进程正常结束,子进程的管道会自动关闭吗?

另外,如果子进程也有一个子进程并且子进程以段错误结束,它是否也会杀死我的孙进程?我的意思是从进程表中删除它(我不需要等待它)。

编辑: 例如,对于以下代码,我在子进程中生成了一个段错误,并尝试在父进程中等待它。运行程序后,waitpid 返回-1,但是当我检查 WIFEXITED(status) 时,子进程程序似乎正常退出。 我得到了一个

Killing child process failed: No such process

错误试图杀死我的孙进程。我想知道这是否是因为段错误会自动关闭子进程和孙进程?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>


int main( void ) {

    pid_t childpid;
    int ends[ 2 ];
    pipe( ends );
    if ( ( childpid = fork() ) == -1 ) {
        perror( "fork failed" );
        exit( 0 );
    }
    if( childpid == 0 ) {
        pid_t cpid;
        if ( ( cpid = fork() ) == -1 ) {
            perror( "fork failed" );
            exit( 0 );
        }
        if ( cpid == 0 ){
            while(1);
        }   
        else{
            printf("cpid is : %d\n",cpid);
            char msg[32];
            sprintf( msg, "%d", cpid );
            printf("cpid con is : %s\n", msg);
            if( write( ends[ 1 ], msg, 32 ) == -1 ) {
                perror( "Write failed" );
                exit( 0 );
            }
            char *s = NULL;
            *s = 15;
            while(1);
        }
    }
    else{
        printf("childpid is : %d\n",childpid);
        char msg[ 32 ];
        int cpid;
        if( read( ends[0], msg,32 ) == -1 ) {
            perror("read failed");
            exit( 0 ); 
        }
        cpid = atoi( msg );
        int status;
        while(1) {
            if ( waitpid( childpid, &status, WNOHANG ) == -1 ) {
                //printf( "%d\n", WIFEXITED(status) );
                if ( kill( cpid, 9 ) == -1 ) {
                    perror( "Killing child process failed" );
                    exit( 0 );
                }
                /*if ( kill( cpid, 9 ) == -1 ) {
                    perror( "Killing child process failed" );
                    exit( 0 );
                }*/

            }
        }
    }
    return 0;
}

最佳答案

操作系统将关闭与已终止或退出的进程关联的所有文件描述符。如果这关闭了指向管道读取端的最后一个文件描述符,那么写入写入端将开始生成 SIGPIPE(fds 是对它们后面的 vnode 实体的引用计数引用)。

如果父进程结束,其 child 将重新成为 init 的 parent 。 init 将等待它。 (无论如何,祖 parent 不能等待)。

关于c - 退出程序会不会自动关闭管道?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35879838/

相关文章:

c - 使用系统调用 fork() execvp() wait() pipe() 实现多管道 - 它根本不起作用

c - scanf() 可变长度说明符

.net - 尝试获取进程的窗口句柄的异常消息

linux - Xlib 是否对 Window 关联的进程 ID 有任何库调用?

C - 通过 execve 传递管道

c - 在 C 中处理管道

c - 如何设置C盘

c - 函数返回局部变量的地址,但仍在c中编译,为什么?

python - tp_clear、tp_dealloc 和 tp_free 之间有什么区别?

c# - 如何以托管方式在 .NET 中获取父进程