[英]C++ How to prevent child process binding port after fork() on Linux?
I have a "launcher" programs that listens to port X, and then starts other processess with fork() 我有一个“启动器”程序,它监听端口X,然后使用fork()启动其他进程
signal(SIGCHLD, SIG_IGN);
a.sin_port=htons(atoi(argv[1]));
if(bind(os,(struct sockaddr *)&a,sizeof(a)) == -1) {
if(Debug){
printf("Launher: Can't bind our address (%s)\n", argv[1]);
}
exit(1);
}
Fork: 叉子:
int pid = fork();
if ( pid == 0 )
{
execl( "udp-proxy/udp_proxy","udp-proxy/udp_proxy",listenPort.c_str(),listenClient.c_str(),listenHost.c_str(),nullptr );
}
However, afrer I restart the "launcher", it shows a message: "Launher: Can't bind our address". 但是,在重新启动“启动器”之后,它显示一条消息:“启动器:无法绑定我们的地址”。
I checked with "lsof -i UDP", and it seems that child processes are listening to this port, so it can't be binded again. 我检查了“ lsof -i UDP”,似乎子进程正在侦听此端口,因此无法再次绑定该端口。 Is it possible to prevent child process using the same binded sockets?
是否可以防止子进程使用相同的绑定套接字? I read something about "file descriptors" but I don't know how to prevent it :(
我读了一些有关“文件描述符”的内容,但我不知道如何防止它:(
Thanks to @Dietrich Epp for solution. 感谢@Dietrich Epp提供解决方案。
Adding SOCK_CLOEXEC flag fixes the problem. 添加SOCK_CLOEXEC标志可解决此问题。
Before: 之前:
int os=socket(PF_INET,SOCK_DGRAM,IPPROTO_IP);
After: 后:
int os=socket(PF_INET,SOCK_DGRAM|SOCK_CLOEXEC,IPPROTO_IP);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.