Lunar Mushrooms
Lunar Mushrooms

Reputation: 8958

How to detect program termination in C/Linux?

How can an application find out that it just started terminating ? Can I use signal handler for that ?

Upvotes: 2

Views: 2473

Answers (4)

sujin
sujin

Reputation: 2853

Enable atexit(). It will call a function when program terminated normally.

Sample code:

#include <stdio.h>      
#include <stdlib.h>    
void funcall(void);
void fnExit1 (void)
{
  printf ("Exit function \n");
}

int main ()
{
  atexit (fnExit1);
  printf ("Main function start\n");
  funcall();
  printf ("Main function end\n");
  return 0;
}

void funcall(void)
{
    sleep(2);
    exit(0);
}

Output:

Main function start
Exit function 

Upvotes: 1

Adi
Adi

Reputation: 731

You can install a signal handler for SIGINT ,SIGKILL and SIGSEGV. In the signal handler you can take a stack dump so you can debug your application later.In the signal handler set the disposition of SIGINT ,SIGKILL and SIGSEGV back to default.

Upvotes: 0

Sakthi Kumar
Sakthi Kumar

Reputation: 3045

You can also register a function to be called upon exit of a process. See man atexit

Upvotes: 0

Ansh David
Ansh David

Reputation: 672

You Could try ---> int raise (int sig)

And handle when SIGTERM or SIGKILL is raised!!

Upvotes: 0

Related Questions