流程从空调系统命令来启动继承父FD的 [英] Process started from system command in C inherits parent fd's

查看:206
本文介绍了流程从空调系统命令来启动继承父FD的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个SIP服务器监听TCP和UDP端口5060的示例应用程序。
同时在code某一点上,我做一个系统(pppd的文件/ etc / ppp / myoptions&安培;);

I have a sample application of a SIP server listening on both tcp and udp ports 5060. At some point in the code, I do a system("pppd file /etc/ppp/myoptions &");

在此之后,如果我做了netstat的-apn,这说明我的端口5060也被打开了pppd的!
有没有什么方法来避免这种情况?在Linux的系统函数的这个标准的行为呢?

After this if I do a netstat -apn, It shows me that ports 5060 are also opened for pppd! Is there any method to avoid this? Is this standard behaviour of the system function in Linux?

谢谢,
Elison

Thanks, Elison

推荐答案

是,默认情况下,当你创建一个进程(其中系统一样),孩子继承所有父母的文件描述符。如果孩子并不需要这些描述符,它应该关闭它们。与系统(或调用fork + EXEC任何其他方法)是设置FD_CLOEXEC标志上不应该被用于所有文件描述符的方式做到这一点你的孩子处理。这将导致它们被自动关闭,只要任何一个孩子的高层其他程序。

Yes, by default whenever you fork a process (which system does), the child inherits all the parent's file descriptors. If the child doesn't need those descriptors, it SHOULD close them. The way to do this with system (or any other method that does a fork+exec) is to set the FD_CLOEXEC flag on all file descriptors that shouldn't be used by the children of you process. This will cause them to be closed automatically whenever any child execs some other program.

在一般情况下,任何时候你的程序打开文件描述符的任何种类的会活的很长一段时间(比如在你的榜样监听套接字),并且不应该与孩子分享,你应该做的

In general, ANY TIME your program opens ANY KIND of file descriptor that will live for an extended period of time (such as a listen socket in your example), and which should not be shared with children, you should do

fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);

在文件描述符。

随着2016年的? POSIX.1修订,您可以使用 SOCK_CLOEXEC 标志或运算插入插座的类型自动获得这种行为,当您创建套接字:

As of the 2016? revision of POSIX.1, you can use the SOCK_CLOEXEC flag or'd into the type of the socket to get this behavior automatically when you create the socket:

listenfd = socket(AF_INET, SOCK_STREAM|SOCK_CLOEXEC, 0);
bind(listenfd, ...
listen(listemfd, ...

这guarentees它就会被关闭,即使其他一些同时运行的线程做了系统 + EXEC 电话。幸运的是,这个标志已经支持一段时间在Linux和BSD Unix系统(而不是OSX,可惜)。

which guarentees it will be closed properly even if some other simultaneously running thread does a system or fork+exec call. Fortunately, this flag has been supported for awhile on Linux and BSD unixes (but not OSX, unfortunately).

这篇关于流程从空调系统命令来启动继承父FD的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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