1. Realization of basic signal processing
Sigaction memory zeroed before use
2. Implementing the underlying Process model
Wait waits for the child process to end
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "Common.h"
#include "serversignal.h"
static volatile sig_atomic_t graceful=0;
int main (int argc, char *argv[])
{
Signal_init ();
int max_worker= 5;
int child = 0;
while (!graceful&&!child) {
if (max_worker>0) {
Switch (fork ()) {
Case-1:
return-1;
Break
Case 0:
Child = 1;
Break
Default
printf ("Child creat\n");
max_worker--;
Break
}
}else{
int status = 0;
if (-1 = Wait (&status)) {
max_worker++;
printf ("Parent wakeup\n");
}
}
}
if (!child) {
printf ("Quit Kill children first\n");
Kill (0, SIGINT);
Sleep (20);
}else{
Sleep (5);
printf ("Child quit\n");
}
return 0;
}
void Server_graceful_set (int g)
{
if (g>0) {
g=1;
}else{
g=0;
}
graceful=g;
}
int Server_graceful_get ()
{
return graceful;
}
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "serversignal.h"
#include "Server.h"
typedef void (*sig_hanlder) (int SIG);
struct server_signal{
int sig;
Sig_hanlder handler;
};
static int Signal_handler (int sig);
#define Sig_map_gen (SIG, Hanlder) {sig, Hanlder},
#define SIG_MAP (XX) \
{\
XX (SIGINT, Signal_handler) \
XX (SIGHUP, Signal_handler) \
XX (0, NULL) \
}\
int Signal_init ()
{
int index = 0;
struct server_signal signals[]=sig_map (Sig_map_gen);
while (Signals[index].sig! = 0) {
struct Sigaction Act;
memset (&act, 0, sizeof (struct sigaction));
Act.sa_handler= (Signals[index].handler);
Sigemptyset (&act.sa_mask);
Sigaction (Signals[index].sig, &act, NULL);
index++;
}
return 0;
}
static int Signal_handler (int sig)
{
int status=0;
Switch (SIG) {
Case SIGINT:
Server_graceful_set (1);
Break
Case SIGHUP:
printf ("sighup\n");
Break
Case SIGCHLD:
if (server_graceful_get () = = 1) {
while (Wait (&status) >0) {};
}
Break
Default
Break
}
return 0;
}
#ifndef common_h_included#definecommon_h_included#include<stdio.h>#include<stdlib.h>#include<unistd.h>#include<signal.h>#include<sys/socket.h>#include<sys/types.h>#include<string.h>typedefenum { true=1, false=0}boolean;enumlogmode{Server_log_file=0, server_log_stderr};structserver{enumlogmode Svlogmode;};#defineASSERT (P) Do{ if(!p) {printf ("assert error at%s,%d. \ n", __file__, __line__); } } while(0)#endif //common_h_included