Reputation: 541
I have a command line application. The issue I am facing is that sometimes the users of that application close directly the terminal in which our application is running that also using the below command:
kill -9 pid_of_parent_console
I the above case our application should close gracefully by doing all the necessary cleanup. For that I wrote a signal handler for handling SIGHUP signal as when controlling terminal of process exits it sends SIGHUP to processes running under it, which we have handled to exit our process gracefully.But the thing is if user open a terminal suppose that is by default bash and then he again types bash command in it then run our application and if suppose kills that applications parent process that is bash executed manually after opening terminal then our application doesn't gets SIGHUP and does not exit gracefully.For simplicity I have written the below code which reproduces the issue:
#include <stdio.h>
#include <signal.h>
FILE *fp = NULL;
int flag = 1;
void handler(int signum)
{
flag = 0;
}
int main()
{
signal(SIGHUP, handler);
// just for testing
fp = fopen("file", "w");
// loop terminates only when HUP is generated
while (flag);
// if SIGHUP is generated then code should reach here
// and write the below in file.
fprintf(fp, "SIGHUP Generated");
fclose(fp);
return 0;
}
For simplicity I am not using sigaction for handling signals.
What I have observed is that when I open a terminal and press tty command and note the name of stdin file associated with it, and then when in the same terminal if I enter bash command and again if I note down the stdin file associated with it using tty command, what I found out is that both the bash shells, one that opens by default when I launch terminal and one I manually opened by typing bash command in bash console share the same stdin file name.
So, due to which when I kill that second bash which is parent of my process the stdin file associated with it doesn't gets closed and I think thats why I am not receiving SIGHUP signal.
Is there any other way I can use to kill my process too gracefully when its controlling console gets killed.
Terminal emulator used: GNOME Terminal 2.31.3 Default shell: bash
Upvotes: 0
Views: 1068
Reputation: 30823
Regardless of the OS, SIGKILL
(i.e. signal -9
) is directly handled by the kernel and the process is killed before any userland handler had a chance to process anything. This is true for the Linux kernel just like the Solaris one.
There is then no way for the target process to protect itself against that signal (outside intercepting it on the sender side or in the kernel).
On the other hand, closing a terminal emulator window send an XEvent to it. Before exiting, the terminal emulator should probably send a SIGHUP signal to your process.
I would suggest to use dtrace on the Solaris 10 machine to investigate this process. Start with this script which show all signals sent: http://www.brendangregg.com/DTrace/kill.d
Upvotes: 1