The question in the title is, after a fork(), how close the listening socket in the child process?
Minimal example:
#include "crow.h"
#include <thread>
#include <sys/wait.h> // waitpid
#include <sys/types.h> // pid_t
void thr()
{
pid_t pid = fork();
if (pid == 0)
{
/*
* How here close the listening socket in the child process?
*/
for (int i = 0; i < 10; i++)
{
sleep(1);
}
exit(0);
}
else if (pid == -1)
{
printf("Error fork() - %s\n", strerror(errno));
}
else
{
printf("Process %d started\n", pid);
int status;
pid_t result = waitpid(pid, &status, 0);
if (result == pid)
{
if (WIFEXITED(status))
{
printf("Process %d return %d\n", pid, WEXITSTATUS(status));
}
else if (WIFSIGNALED(status))
{
printf("Process %d killed signal %d - %s\n", pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
}
}
else
{
printf("Error waitpid() - %s\n", strerror(errno));
}
}
}
int main()
{
crow::SimpleApp app;
CROW_WEBSOCKET_ROUTE(app, "/test_ws")
.onopen([&](crow::websocket::connection& conn)
{
printf("/test - New websocket connection from %s\n", conn.get_remote_ip().c_str());
std::thread t(thr);
t.detach();
})
.onclose([&](crow::websocket::connection& conn, const std::string& reason, uint16_t err)
{
printf("/status_ws - Websocket connection closed: %s, %s\n", std::to_string(err).c_str(), reason.c_str());
})
.onmessage([&](crow::websocket::connection& conn, const std::string& data, bool is_binary)
{
}
);
CROW_ROUTE(app, "/test")
([]
{
std::string content = "<!DOCTYPE html>"
"<html>"
"<body>"
"<button id=\"connect\" onclick=\"connectWebSocket()\">Connect</button>"
"<script>"
"function connectWebSocket() {"
"const wsUrl = `ws://192.168.18.111:18080/test_ws`;"
"websocket = new WebSocket(wsUrl);"
"}"
"</script>"
"</body>"
"</html>";
return crow::response(200, content);
}
);
app.bindaddr("0.0.0.0")
.port(18080)
.multithreaded()
.run();
return 0;
}
Thanks.
The question in the title is, after a fork(), how close the listening socket in the child process?
Minimal example:
Thanks.