拆分服务器进程的最佳方式

Best Way to Split Server Process

我正在用 C 构建一个服务器,它不仅可以侦听传入连接,还可以为我提供交互式 shell。基本上,我有这样的东西来接受客户...

while (1) {
    accept_client(serverfd);
}

还有类似这样的用于创建交互式 shell

while (1) {
    printf("shell> ");
    fgets(command, sizeof(command) - 1, stdin);
    server_do(command);
}

我想 运行 两个并行循环,交互式 shell 是从服务器实时访问变量。我尝试使用 fork, which worked well, but was overall was not successful, since fork only creates a copy of the child process, and none of the variables can be updated as new connections happen. I also tried using a pipe to transmit data - but that was sort of a disaster (although I may have been doing it wrong). Finally I attempted to use pthread,但没有看到任何明显的方法可以使两个 运行 并行而不阻塞。

执行此操作的“正确”方法是什么?我已经做了相当多的研究,并没有偶然发现一个明显的答案。

您也可以将 'stdin' 视为 'network connection',它们在 low-level 视图中都是“fd”。

所以你需要实现一个服务器来处理并行的多个连接, 有很多方法可以做到这一点。

这里有一本很好的读物 (http://www.wangafu.net/~nickm/libevent-book/01_intro.html),用于解释和比较这些方法。

我想在您的情况下以异步方式实施。 我写了一些包装器和示例 (https://github.com/grizzlybears/tevpp) 以使 libevent 更易于使用。 'cat' 示例演示如何像正常连接一样处理 stdio。您可能有兴趣。:)