-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
97 lines (79 loc) · 2.89 KB
/
Copy pathmain.cpp
File metadata and controls
97 lines (79 loc) · 2.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: arybarsk <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/05/16 20:58:50 by arybarsk #+# #+# */
/* Updated: 2025/05/16 20:58:55 by arybarsk ### ########.fr */
/* */
/* ************************************************************************** */
#include <cstdio>
#include "Server.hpp"
#include "commandLineUtils.cpp"
volatile sig_atomic_t g_oOn = 1;
volatile sig_atomic_t g_sigCaught = 0;
void handle_sig(int sig)
{
g_oOn = 0;
g_sigCaught = sig;
}
// this: struct sigaction sa = {};
// would be better instead of memset (cleaner, more type-safe)
// but in C++98, this is technically not standard.
// with SA_RESTART the system automatically checks if errno == EINTR
// for every syscall like poll() interrupted by a signal
// sigemptyset() is forbidden in the subject
// otherwise, this line would allow only SIGINT during handler:
// sigemptyset(sa.sa_mask);
// here we can live without it because we memset() the whole struct to zero
// which is effectively the same as sigemptyset()
// SIGINT is Ctrl-C
// SIGTERM is in kill command:
// ps aux | grep ircserv
// kill -SIGTERM <process number>
// SIGPIPE is ignored so send/recv errors can be handled in code, not via signals
int main(int argc, char **argv)
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = handle_sig;
sa.sa_flags = SA_RESTART;
if (sigaction(SIGINT, &sa, NULL) == -1
|| sigaction(SIGTERM, &sa, NULL) == -1)
{
perror("sigaction");
return (1);
}
struct sigaction sa_pipe;
memset(&sa_pipe, 0, sizeof(sa_pipe));
sa_pipe.sa_handler = SIG_IGN;
sa_pipe.sa_flags = 0;
if (sigaction(SIGPIPE, &sa_pipe, NULL) == -1)
{
perror("sigaction(SIGPIPE)");
return (1);
}
try
{
int port;
std::string password;
if (!parseCommandLineArgs(argc, argv, port, password))
return (1);
Server server(port, password);
server.getGoing();
if (g_sigCaught == SIGINT)
std::cout << "Caught SIGINT, server shutting down" << std::endl;
else if (g_sigCaught == SIGTERM)
std::cout << "Caught SIGTERM, server shutting down" << std::endl;
else
std::cout << "Caught unknown signal: (" << g_sigCaught << "), server shutting down" << std::endl;
}
catch (const std::exception& e)
{
std::cerr << "Server exception: " << e.what() << std::endl;
return (1);
}
return (0);
}