如何将套接字从父进程传递给子进程 [英] How can I pass a socket from parent to child processes

查看:102
本文介绍了如何将套接字从父进程传递给子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Linux上的C程序中遇到了问题.

I'm stuck on a problem in a C program on Linux.

我知道,当一个进程被派生时,子进程会从父进程那里继承一些东西,包括 open 文件描述符.

I know that when a processes is forked the child process inherits some things from the parent, including open file descriptors.

问题是我正在编写一个具有主进程的多进程服务器应用程序,该主进程接受新连接并将描述符放入共享内存中.

The problem is that I'm writing a multi-process server application with a master process that accepts new connections and puts the descriptors into shared memory.

当子进程尝试从共享内存中读取这些描述符之一时,在 select()上,我收到了 EBADF 错误!

When the child process attempts to read from one of these descriptors from the shared memory, on select() i got an EBADF error!

子进程在分叉后如何读取和使用由父进程创建的套接字(通常是任何文件描述符)?

How can the child process read and use a socket (or any file descriptor in general) created by a parent process after it has been forked?

推荐答案

调用fork时,子进程将继承所有打开的文件描述符的副本.典型的做法是让父进程打开一个监听套接字,调用accept阻塞直到连接到达,然后在接收到连接后调用fork.父级然后关闭它的文件描述符副本,而新的子进程可以继续使用文件描述符并进行所需的任何处理.子级完成后,会关闭套接字.重要的是要记住两件事:1.文件描述符/套接字是操作系统中的一种资源,在派生之后,父级和子级都具有对该资源的句柄,有点像引用计数的智能指针.我在这里详细解释.第二件事是,仅共享在调用fork之前 打开的文件描述符,因为分叉后的父子进程是完全独立的进程,即使它们可能共享某些资源(例如文件描述符之前存在的资源)叉.如果您使用的模型中希望父母将工作交给工作进程,则最好考虑使用线程,并且

When you call fork, the child process inherits copies of all open file descriptors. The typical way of doing this is for a parent process to open a listening socket, call accept which blocks until a connection arrives and then calls fork after receiving the connection. The parent then closes it's copy of the file descriptor, while the new child process can keep using the file descriptor and do any processing which is needed. Once the child is done it also closes the socket. It's important to remember two things: 1. The file descriptor / socket is a resource in the operating system and after the fork the parent and child each have a handle to that resource, which is kind of like a reference counted smart pointer. I explain this in more detail here. The second thing is that only file descriptors which are opened before calling fork are shared, because after forking parent and child are completely separate processes, even though they may share some resources like file descriptors which existed prior to the fork. If you're using a model where you want to have a parent handing out work to worker processes, it may be better for you to consider using threads, and a thread pool.

顺便说一句,您可以从 Unix网络编程网站下载服务器和客户端的精美示例的分配.

By the way, you can download allot of nice examples of servers and clients from Unix Network Programming website.

这篇关于如何将套接字从父进程传递给子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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