父母与分叉的孩子之间的文件描述符共享 [英] File Descriptor Sharing between Parent and Pre-forked Children

查看:93
本文介绍了父母与分叉的孩子之间的文件描述符共享的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Unix网络编程中,有一个预分支服务器的示例,该服务器使用在Unix域管道上传递的消息来指示子进程处理传入连接:

In Unix Network Programming there is an example of a Pre-forked server which uses message passing on a Unix Domain Pipe to instruct child processes to handle an incoming connection:

for ( ; ; ) {
    rset = masterset;
    if (navail <= 0)
        FD_CLR(listenfd, &rset);    /* turn off if no available children */
    nsel = Select(maxfd + 1, &rset, NULL, NULL, NULL);

        /* 4check for new connections */
    if (FD_ISSET(listenfd, &rset)) {
        clilen = addrlen;
        connfd = Accept(listenfd, cliaddr, &clilen);

        for (i = 0; i < nchildren; i++)
            if (cptr[i].child_status == 0)
                break;              /* available */

        if (i == nchildren)
            err_quit("no available children");
        cptr[i].child_status = 1;   /* mark child as busy */
        cptr[i].child_count++;
        navail--;

        n = Write_fd(cptr[i].child_pipefd, "", 1, connfd);
        Close(connfd);
        if (--nsel == 0)
            continue;   /* all done with select() results */
}

如您所见,父级将套接字的文件描述符号写入管道,然后在文件描述符上调用close.当预分支的子代完成套接字时,它们还将在描述符上调用close.让我陷入循环的是,因为这些子项是预分叉的,所以我假设只共享那些在子项被分叉时存在的文件描述符.但是,如果这是真的,那么此示例将严重失败,但仍然有效.

As you can see, the parent writes the file descriptor number for the socket to the pipe, and then calls close on the file descriptor. When the preforked children finish with the socket they also call close on the descriptor. The thing which is throwing me for a loop is that because these children are preforked I would assume that only file descriptors which existed at the time the children were forked would be shared. However, if that was true, then this example would fail spectacularly, yet it works.

有人能阐明父分叉创建的文件描述符在分叉后最终与子进程共享的情况吗?

Can someone shed some light on how it is that file descriptors created by the parent after the fork end up being shared with the children process?

推荐答案

看看Write_fd实现.它使用类似

Take a look at the Write_fd implementation. It uses something like

union {
  struct cmsghdr        cm;
  char                          control[CMSG_SPACE(sizeof(int))];
} control_un;
struct cmsghdr  *cmptr;

msg.msg_control = control_un.control;
msg.msg_controllen = sizeof(control_un.control);

cmptr = CMSG_FIRSTHDR(&msg);
cmptr->cmsg_len = CMSG_LEN(sizeof(int));
cmptr->cmsg_level = SOL_SOCKET;
cmptr->cmsg_type = SCM_RIGHTS;
*((int *) CMSG_DATA(cmptr)) = sendfd;

也就是说,发送类型为SCM_RIGHTS的控制消息是Unix可以与不相关进程共享文件描述符的一种方式.

That is, sending a control message with type SCM_RIGHTS is a way unixes can share a file descriptor with an unreleated process.

这篇关于父母与分叉的孩子之间的文件描述符共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆