Assuming this program is running in background.
Assuming headers are included e.g signal.h…
void SignalHandler(int sig);
int fd;
int main(int argc, char *argv[]){
signal(SIGINT,SignalHandler);
signal(SIGHUP,SignalHandler);
signal(SIGTERM,SignalHandler);
setsid();
close(0);
close(1);
close(2);
fd = open("/myPIPE", O_RDWR);
if(fd<0){
perror("open() error");
exit(1);
}
while (1) {
err = read(fd, strbuf, 256);
if(err)
syslog(LOG_INFO,"%s",strbuf);
}
close(fd);
}
void SignalHandler(int sig){
if(fd!=-1)
close(fd);
exit(0);
}
Assuming that this code is already running. and has program name of testsignal. When i run it again in the terminal ./testsignal & the process just keeps on adding up.. the currently running process should exit and the new process should replace the old one. so only process should be running. I need help on this. Thanks
This code is a simplification of yours in that it doesn’t use
syslog(). It also doesn’t close standard input, standard output and standard error, so the daemon still has a way to log information to standard output (specifically). This makes it easier for me to test.The
flprintf()function is used to ensure that all outputs to standard output are flushed; it reduces the number of boring 4-line blocks of code in the program. The program also logs more of its activity, which also makes it easier to see what’s going on. (In part that’s because I managed to overlook the commented-outclose()system calls.) I make everything that doesn’t have to be visible outside of this source file static; that means onlymain()is not static. This code also ensures that the string read is null terminated, so long strings followed by short ones don’t produce messages that are a mish-mash of the short one plus the remains of the longer ones.I tested on Mac OS X 10.7.5 (GCC 4.7.1, not that it matters much in this case). The only behaviour I found surprising once it was working was that the program didn’t get EOF when the process writing a message to the FIFO closed. However, I think that’s explained by the
O_RDWRon theopen()call; there’s still a process (this one) with the FIFO open. Recompile withO_RDONLYand the process exits after the first time something writes to the pipe…sanity rules. What you’ve done is fine as a way of achieving a FIFO that never reports EOF. (It also explains why the process didn’t block on the open, waiting for a process to open the FIFO.)Sample output: