Link to home
Start Free TrialLog in
Avatar of tonitop
tonitop

asked on

Signal handling in unix

I have TCPSocket class which offers method connect, close, read
and write (probably no need to explain them :). I have been using roquewave to implement this class.

Now I would like to add a signal handler to my class, which notifies the user when SIGPIPE is received. I have been looking into man pages,
but can't figure out how to do it.

So what I would like is a simple example (maybe a class) which has
a signal handler and some explanation how it works.
Avatar of proskig
proskig

Hi,
It is not hard at all. First of all check man pages for signal. I have them in 3b,3c and 5 sections. You have to have your signal handler, let's say
void sig_handler(int signum);
Then just call
signal(SIGPIPE,sig_handler);
to install your handler.
ASKER CERTIFIED SOLUTION
Avatar of bcoleman
bcoleman

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
man sigprocmask (or sigthreadmask if you're using multiple threads) should get you started.

My suggestion however would be to use errno (include errno.h) most system calls set errno when a system call fails.  This will make your TCPSocket class reusable (signal handling is for an entire process, anyone who is already using signal handling won't want to use your object because it will replace their signal handling with yours).  Making a call to strerror with the errno will give you the error text equivalent.

sample code:

  #include <errno.h>

  ...

  if((fd = open("test.txt","r",0)) == -1)
    {
       cout << "error: " << strerror(errno) << endl;
    }
One thing to keep in mind using proskig's suggestion: if you want to make a class' method to handle the signal it has to be a static one, as signals are global to a process.
Avatar of tonitop

ASKER

Ok, the signal handling part works, but how come I don't get the signal right away? I connect to server and write something. Then I close the server. After that I write something and it goes ok and I receive the signal when I try to write second time. I have been looking into select() function, but can't figure out how I know that the connection has been lost.
Avatar of tonitop

ASKER

So if I wan to handle signals inside my class can it be done?
Isn't static method class method. i.e. they can be used even if no objects have been created.

I would need to somehow set a flag inside my object when it receives signal, but I can not do that with static methods.
Avatar of tonitop

ASKER

Comment accepted as answer