LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to detect broken pipe in C (Linux)? (https://www.linuxquestions.org/questions/programming-9/how-to-detect-broken-pipe-in-c-linux-292898/)

alanwolfen 02-21-2005 04:41 AM

How to detect broken pipe in C (Linux)?
 
I am using pipes for IPC and have a main program opening pipes for 2 other processes. Each process is connected the main program by 2 pipes (read and write)

main <=a== process 1
main ==b=> process 1

The main program will wait at the read end of pipe a. When a process connects, the main program will open the write end of pipe b which process 1 had already opened.

Let's say process 1 terminates unexpectedly, then the main program crashes due to broken pipe b. Now the question is having 2 process connecting to main with 2 pairs of read-write pipes, how do main detect which pipe is broken and closes it without crashin?

Raghavendra_M 02-21-2005 08:46 AM

using signal
 
You can try catching the signal "SIGPIPE". You can register to get this signal using the system call "signal".

Hope this solves your problem.

alanwolfen 02-21-2005 07:36 PM

I have thought of signals, but it doesn't allow me to identify which pipe causes the error and to close it. I dun wan to close all pipes and reopen all of them.

Anyone to identify the pipe's FD if we are to use the signal handler's approach?

Raghavendra_M 02-22-2005 07:57 AM

As you might be knowing the signal SIGPIPE is sent to the process which is trying to write into a pipe which has no readers.

In your case, to identify the exact pipe which is closed probably you can do the following:

- ignore the SIGPIPE signal i.e.

Code:

signal(SIGPIPE,SIG_IGN); //ignoring the broken pipe signal
- now whenever a reader process exits, since writer process has opted to ignore the signal whenever writer tries to write into the pipe the "write" system call will fail & returns error (-1). The exact reason for the failure of "write" can be got if required ("errno" will be set to "EPIPE").

Hope this will solve your problem.

alanwolfen 02-23-2005 01:22 AM

Yes it solves my problem! Thanks.


All times are GMT -5. The time now is 12:14 AM.