套接字描述符被传递给分叉进程
我有一个运行 shell 脚本的 C 应用程序。 C 程序使用以下逻辑(在较高级别):
- C 应用程序侦听端口 7791,将此称为“webClient”。
- 一旦 webClient 通过端口 7791 获取数据,除其他外,它会调用 fork 命令。
- 在子进程内,使用我的 shell 脚本运行 execve。
- shell 脚本执行各种活动,包括启动另一个不应侦听任何端口(根本不使用套接字)的 C 守护程序。将此 C 守护进程称为“emaildae”。仅启动了一个守护进程,显然是在后台启动的。
- webClient 应用程序等待子进程完成,报告任何问题。
- webClient 应用程序返回到侦听端口 7791。
当我运行 netstat -nlp | grep 7791,我看到 webClient 正在监听,正如我所期望的那样。当我杀死 webClient 时,我现在看到 emaildae 正在端口 7791 上侦听(再次使用 netstat)。我尝试使用 nohup
和 disown
启动 emaildae,但既没有 nohup
本身,也没有 nohup
与 disown解决问题。我尝试在子进程中使用 close(socketFd) 关闭套接字,就像我在其他地方所做的那样,但这也不起作用。我从各种网络搜索中知道套接字描述符与所有文件描述符一起传递给子进程。我不知道如何防止这种情况发生。也许是我关错了。如果有一种方法可以在不影响父进程的情况下关闭套接字描述符,那么可能会解决问题。有什么想法吗?
I have a C application that runs a shell script. The C programs uses the following logic (at a high level):
- C application listens on port 7791, call this "webClient".
- Once webClient gets data via port 7791, among other things, it calls the fork command.
- Inside child process, run execve with my shell script.
- The shell script does various activities, including starting another C daemon that should not be listening on any ports (does not use sockets at all). Call this C daemon "emaildae". Only one daemon is started, obviously in the background.
- The webClient application waits for child process to finish, reporting any problems.
- The webClient application goes back to listening on port 7791.
When I run netstat -nlp | grep 7791
, I see webClient listening, as I would expect. When I kill webClient, I now see emaildae listening on port 7791 (using netstat again). I have tried starting emaildae using nohup
and disown
, but neither nohup
by itself nor nohup
with disown
solve the problem. I tried closing the socket using close(socketFd)
in the child process, like I do in other places, but that did not work either. I know from various web searches that the socket descriptor gets passed to child processes, along with all file descriptors. What I don't know is how to prevent this from happening. Maybe I closed it wrong. If there is a way to close the socket descriptor without impacting the parent process, that might fix things. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实证明@Barmer 是正确的,我关闭了错误的文件描述符。一旦我关闭了监听套接字文件描述符,它就起作用了。
另外,这是更完整的答案的重复 - 我错过了它,直到我看到@Barmer的措辞。
在我的例子中,我执行以下操作:
listeningSocketFd
fork
close(listeningSocketFd) ;
我现在在父进程中什么也不做。不确定这是否会给我带来问题。
It turns out @Barmer was correct, I was closing the wrong file descriptor. Once I closed the listening socket file descriptor, it worked.
Also, this is a repeat of a more complete answer - I missed it until I saw @Barmer's phrasing.
In my case, I do the following:
listeningSocketFd
fork
close(listeningSocketFd);
I do nothing in the parent process right now. Not sure if that will cause me problems or not.