If you are trying to figure out how to make a server not terminate in C, the most important idea is that a long-running C server must be designed so that temporary errors, abnormal client behavior, and operating system signals do not cause the main program to exit. A dependable C server should keep running unless you explicitly tell
it to stop. The usual way to achieve that is to separate normal server lifetime from per-client work. The main server loop should keep accepting connections, while each client connection is treated as a temporary task that can fail, disconnect, time out, or behave badly without killing the whole process Less friction, more output..
1. Keep the main loop running
A simple server often looks like this:
while (1) {
int client = accept(server_fd, NULL, NULL);
if (client < 0) {
perror("accept");
exit(1);
}
handle_client(client);
close(client);
}
The problem is that accept() can fail for reasons that should not terminate the server. Consider this: for example, it may be interrupted by a signal. In that case, errno is usually EINTR, and the correct action is to retry.
A safer version is:
for (;;) {
int client = accept(server_fd, NULL, NULL);
if (client < 0) {
if (errno == EINTR) {
continue;
}
perror("accept");
/*
* Some accept errors are recoverable. Others may indicate a serious
* problem. Decide based on your application requirements.
handle_client(client);
close(client);
}
The important rule is: do not call exit() for every error. Only exit when the server can no longer continue safely That's the whole idea..
2. Handle signals properly
A C server can be terminated unexpectedly by signals such as SIGINT, SIGTERM, or SIGHUP. If you want controlled shutdown, use a signal handler that only sets a flag Practical, not theoretical..
#include
#include
#include
#include
static volatile sig_atomic_t stop_server = 0;
void handle_signal(int sig)
{
(void)sig;