简体   繁体   English

分叉的进程一直在监听服务器的端口

[英]Forked process keeps listening to the server's port

This is light version of my code for executing commands: 这是我用于执行命令的代码的简化版本:

void close_all_nonestandard_fds()
{
    struct rlimit fds_limit;
    int max_fd = 1024;
    if (getrlimit(RLIMIT_NOFILE, &fds_limit) == 0) max_fd = fds_limit.rlim_cur;
    for(int i = 0; i <= max_fd; ++i) {
        if(i != STDERR_FILENO && i != STDOUT_FILENO && i != STDIN_FILENO) close(i);
    }
}

void exec_command(char* command, char*const* args)
{
    pid_t pid = fork();
    if(pid != 0)
    {
        if(pid == -1) throw_error("Failed to fork: %s", strerror(errno));
        // Parent
    }
    else
    {
        // Child
        close_all_nonestandard_fds();
        if(execv(command, args) == -1) throw_error("Failed to execv: %s", trerror(errno));
    }
}

The exec_command method is used in my server side application for running different kind of processes including daemon processes. exec_command方法在我的服务器端应用程序中用于运行exec_command的进程,包括守护进程。 But here I noticed a problem: 但是在这里我注意到一个问题:

When server runs a child daemon process, then it (the server) being killed or crashed the child starts to listen to the port server was listening to. 当服务器运行子守护进程时,子(守护程序)被杀死或崩溃,子进程开始监听服务器正在监听的端口。

So, how can I execute a command and be sure that it wouldn't keep port of the server busy after servers end (crash, death)? 因此,如何执行命令并确保在服务器结束后(崩溃,死亡)它不会使服务器的端口繁忙?

Just keep track of all server sockets by storing them and then after fork() ing have those close() d in the child. 只需通过存储所有服务器套接字来跟踪它们 ,然后在fork()后在子进程中包含那些close()

Those are the listen() ing sockets and the accept() ed sockets. 这些是listen()套接字和accept()套接字。


Update: 更新:

Also you might like to use setsockopt() to set the option SO_REUSEADDR to the socket passed to bind() 另外,您可能想使用setsockopt()将选项SO_REUSEADDR设置为传递给bind()的套接字

SO_REUSEADDR SO_REUSEADDR

Indicates that the rules used in validating addresses supplied in a bind(2) call should allow reuse of local addresses. 指示用于验证bind(2)调用中提供的地址的规则应允许重用本地地址。 For AF_INET sockets this means that a socket may bind, except when there is an active listening socket bound to the address. 对于AF_INET套接字,这意味着套接字可以绑定,除非有活动的监听套接字绑定到该地址。 When the listening socket is bound to INADDR_ANY with a specific port then it is not possible to bind to this port for any local address. 当侦听套接字通过特定端口绑定到INADDR_ANY时,则不可能为任何本地地址绑定到此端口。 Argument is an integer boolean flag. 参数是一个整数布尔值标志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM