How to implement SIGKILL and SIGTERM and print a message?


 
Thread Tools Search this Thread
Top Forums Programming How to implement SIGKILL and SIGTERM and print a message?
# 1  
Old 11-08-2007
Question How to implement SIGKILL and SIGTERM and print a message?

Hello,

I am running a webserver that uses sockets, forks, and children. The parent process listens for connections and the child processes the information.

I am trying to figure out why the code I have below SIGTERM, and SIGKILL never fire. I was messing around with the printfs and doesnt seem to be entering the switch for sigterm and sigkill and sighup.

I do have sigint and sighup working.

Can someone help me fix this code so that the server gracefully terminates when a sigkill and sigterm are detected. I was trying to get it so when the signal is recieved to terminate, the printf would write out terminating or something(basically so i know its working).




Code:
//int main code
 //ignore sighup signal, you can log out and server still runs.
    signal(SIGHUP,catcher);

 //stop user from using control c.
    signal(SIGINT, catcher);


    //not working
  //  signal(SIGTERM, catcher);
  //  signal(SIGKILL, catcher);

FUNCTIONS:---------------------------------------------------------------
//gracefully quit on sigterm and sigkill.
void catcher(int sig)
{

  printf ("Caught signal %d\n", sig);
  fflush(stdout);
  switch (sig)
        {
        case SIGINT:

          signal(SIGINT, catcher);
          printf("Control-C not Allowed\n");
          fflush(stdout);
          break;

        case SIGHUP:

          signal(SIGHUP,catcher); /* dont die on sighup */
          printf("SIGHUP Ignored\n");
          fflush(stdout);
          break;


          case SIGTERM:

          signal(SIGTERM, catcher);
          printf("exiting sigterm");
          exit(1);
          fflush(stdout);
          break;

        case SIGKILL:
          printf("sigkilla");
          fflush(stdout);
          signal(SIGKILL, catcher);
          printf("sigkilla");
          exit(1);
          fflush(stdout);
          break;
  }

# 2  
Old 11-08-2007
1. You can't catch SIGKILL by design.

2. You should be able to catch SIGTERM -

Have you unblocked it?
You are calling exit in your signal handler
Have you considered using atexit()

In general two things leap out...

1. you should do the absolute bare minimum in a signal handler, set a flag or a few things, not fflush() or anything the allocates/frees from the heap.

2. use the posix signal handling APIs, sigaction, sigprocmask etc.
# 3  
Old 11-09-2007
Hmmm, I was playing around with a linux firewall and when I closed it down I noticed while the firewall was shutting down, it said, "sending sigkill" "sending sigterm". Thats basically where I got the idea.

Ill have to look in to the unblocking, and the posix. I didnt realize signals where blocked. I thought when i declare in int main to not use default action that would mean the signals have to go through my code.

anyone else feel free to offer opinions.

thanks,
norelco55
# 4  
Old 11-09-2007
Porter is right about keeping things simple in a signal handler. But there is more - do not call most routines in the standard C library - as Porter points out fflush() is one of them.

If you absolutely must do I/O use write(). The idea is that you call something that cannot be interrupted by another signal - this is called an atomic operation.

write() is "partially" guaranteed to be atomic, but is as close as you'll get. POSIX says write() must guarantee a write the size of PIPE_BUF bytes or smaller to be atomic. There are other I/O system calls that are like this.
# 5  
Old 11-09-2007
There are basically two types of signals...

1. synchronous signals, eg SIGSEGV, SIGILL etc

2. asynchronous signals, eg SIGCHLD, SIGQUIT, SIGINT etc

The first type mean something has gone wrong with execution and either you die or have to take some immediate remedy.

The second type are just notifying you that an external event has occured.

I normally structure my async handlers such that the main program is reading input using select or poll and has a pipe dedicated to asynchronous events which I read from.

When a signal occurs I simply write the number of the signal to the write end of the pipe, then let the main loop pickup the notification by reading the pipe and doing the appropriate response during normal processing.
# 6  
Old 11-09-2007
Question

Here is something I had before, which was to ignore control c. How do i unblock a signal? And how is this code? I changed the handler to work with my catcher function now.

Code:
//declare act to deal with action on signal set.
static struct sigaction act;

//setting to my function catcher

 act.sa_handler = catcher;       
 act.sa_flags    = 0;
 
 sigfillset(&(act.sa_mask));      /* create full set of signals */




    //ignore control c and dont hangup when loggedout.
    signal(SIGINT, SIG_IGN);
    signal(SIGHUP, SIG_IGN);


     //Terminate gracefully
     sigaction( SIGTERM, &act, NULL );
     sigaction( SIGKILL  , &act, NULL );


----------------------------------------------------------------
void catcher(int sig)
{

    switch (sig)
        {
          case SIGTERM:

                            signal(SIGTERM, catcher);
                            atexit();
           break;

        case SIGKILL:

                         signal(SIGKILL, catcher);
                         atexit();
          break;
       }
  }

thanks,
Norelco
# 7  
Old 11-09-2007
1. Both sigaction and signal install signal handlers,

(a) don't use both in the same program,
(b) sigaction is the posix one, use that.
(c) With sigaction you don't need to reinstall the signal handler.

2. atexit installs another callback function, so when the program exits politely, through a call to exit you code will get called so you can tidy up.

3. only set flags in the signal handlers, don't do 'work'.

4. you have done sigfillset but done nothing with the sigset_t, you need to call sigprocmask to block or unblock those signals.

5. to ignore a signal, you can

(a) either use SIG_IGN as the callback
(b) or simply block it so it is never delivered to your program.
(c) or get it to call an empty signal handler function

6. compile with maximum warnings, if you are using gcc use "-Wall -Werror", that would have caught your "atexit".

7. And as mentioned, you can't catch SIGKILL, the kernel will just evaporate your process.
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Script to check the string in a file and print an attribute in the message

Hi, I am new to shell scripting and got a task to complete. Task is : we have a log file where in i need to traverse through the whole file to check the string "Person Type missing in message" and after that i need to get EMPLID=xxxxxx from the file and print details in a different file. ... (1 Reply)
Discussion started by: suren424
1 Replies

2. UNIX for Advanced & Expert Users

Print message while using sqlplus

I want to connect to oracle database from solaris... After that i will drop and create a no.of tables.One of the table example is as below. sqlplus -s usrname/password@dbname << SQL >> $logfile 2>&1 echo " dropping the table1" | tee logfile DROP TABLE Table1 echo "creating the table1" |... (1 Reply)
Discussion started by: millan
1 Replies

3. Shell Programming and Scripting

SIGSTOP and SIGKILL

Which is sent to a terminal when it closes? SIGKILL? Reason I ask is I have a script I want to run in the background, but want it to run even if the terminal window is closed. Or, I'd like it to background itself if the terminal is closed but not if its running in an open window. I will learn how... (5 Replies)
Discussion started by: DC Slick
5 Replies

4. Shell Programming and Scripting

How to detect SIGTERM,SIGKILL signal in UNIX

Dear All We have JBOSS server running on Linux we need to track Graceful Shutdown(SIGTERM) and Forceful Shutdown(SIGKILL) timestamp and write it into one file, I am new to UNIX Signal processing if is it possible how to detect it? We generally do $kill PID For Graceful... (5 Replies)
Discussion started by: mnmonu
5 Replies

5. Solaris

SIGQUIT and SIGKILL message

Dear All, I have machine with SunOS 5.10 Generic_138888-01 sun4v sparc SUNW,SPARC-Enterprise-T5120. Yesterday there is something at dmesg command : May 25 18:09:02 cacao_launcher: Timeout occured on heartbeat channel, cleanup engaged May 25 18:09:07 cacao_launcher: watchdog : warning,... (0 Replies)
Discussion started by: mbah_jiman
0 Replies

6. Shell Programming and Scripting

Print a message at specific line on prompt

Hi Friends, I am using HP-UNIX(ksh). I want to print a message at specific line on the prompt screen. For Example: for num in 1 10 3 145 do echo $num // need to print this on the same line for each number sleep 2 done Actual Output: ========== 1 10 3 145 Expected Output:... (5 Replies)
Discussion started by: Niroj
5 Replies

7. Shell Programming and Scripting

Error while trying to print message

Hi all Geting this error while trying to print message as : ./logfunc: print: bad file unit number heres what i m trying to do : log_date="$(date '+%d/%m/%Y %H:%M:%S')" log_type="Message" print "${log_date}: ${log_type}" print -u3 "${log_date}: ${log_type}" this error is due to... (3 Replies)
Discussion started by: Navatha
3 Replies

8. Solaris

To print Coloured Prelogin Message on SOLARIS--9................

Hiiii..... Every one...... I am using /etc/issue file to display Pre-login Message on my system, installed with SOLARIS-9. I am getting this Message in White fonts having Black background ( Colour of the Screen)..... So, is there ... (2 Replies)
Discussion started by: prashantshukla
2 Replies

9. Shell Programming and Scripting

Why SIGKILL will occur?

Hi Gurus, I am executing my Datastage jobs on UNIX operating System. While running the jobs i am getting the following error: main_program: Unexpected termination by Unix signal 9(SIGKILL) Can any one please let me know what are the possible situations where this SIGKILL will arrise? ... (9 Replies)
Discussion started by: choppas
9 Replies

10. Programming

signals - SIGTERM

Hi all, I need some urgent help. we are using Dynix/ptx V4.5 on i386, have several processes and instances are running on the box round the clock.we increased the processes recently. We have coded to handle the signals in our programs. Recently, we noticed most of our processes are... (2 Replies)
Discussion started by: reddyb
2 Replies
Login or Register to Ask a Question