子代写在fork后在父代中创建的文件描述符 [英] Child write on file descriptors created in parent after fork

查看:209
本文介绍了子代写在fork后在父代中创建的文件描述符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父进程监听一个套接字上的传入连接,并且在接受一个客户端之后,它将通过一个命名管道传递相关的文件描述符和一些其他日期给孩子。

I have a parent process which listens for incoming connections on a socket and after accepting a client, It will pass the associated file descriptor and some other date to the child (through a named pipe).

从这一刻开始,子进程将为客户提供服务,父进程将不断监听新客户。

From this moment on, child process will provide service to the client and the parent keeps listening for new clients.

我的问题是,我试图写在子进程中的文件描述符,我会得到一个错误(错误的文件描述符)和写入失败。我的猜测是,由于这些文件描述符是在fork之后创建的,所以child不能简单地使用它们,它们只属于父进程。

My problem is that when I try to write on file descriptors in child process, I will get an error (Bad file descriptor) and write fails. My guess is that since these file descriptors are created after fork, child cannot simply use them and they only belong to the parent process.

?有没有可能的方式让孩子使用这些文件描述符?

So Is this the reason of write failure? Is there any possible way for child to use these file descriptors?



解决方案


正如在loreb的回答中提到的,这是不可能以这种方式实现所需的结果。我做了一个临时修复通过使用另一个管道将指向从子到父的响应。由于文件描述符属于父类,它可以通过套接字将响应转发回客户端。


Solution
As it was mentioned in the answer by loreb, It is not possible to achieve the desired outcome in this manner. I did a temporary fix by using another pipe to direct the response from child to parent. Since file descriptors belong to parent, it can forward the response back to client through a socket.

推荐答案

需要AF_UNIX套接字,而不是命名管道。
你需要sendmsg(3),这是疯狂的使用,所以你最好在网上查找一些例子,例如io_passfd在libowfat。

To pass a file descriptor you need to AF_UNIX sockets, not named pipes. You'll need sendmsg(3), which is insanely weird to use, so you'd better look up some example on the web -- eg io_passfd in libowfat.

编辑:如果任何人绊倒此答案,请不要使用AF_UNIX客户端/服务器,请使用socketpair(2)

in case anyone stumbles upon this answer, don't use an AF_UNIX client/server, use socketpair(2)

这篇关于子代写在fork后在父代中创建的文件描述符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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