Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sun-barr!olivea!uunet!zaphod.mps.ohio-state.edu!caen!uflorida!travis!brad From: brad@SSD.CSD.HARRIS.COM (Brad Appleton) Newsgroups: comp.lang.c Subject: Re: help with popen() Message-ID: <2290@travis.csd.harris.com> Date: 8 Feb 91 21:05:43 GMT References: <1991Feb6.053237.11051@iguana.uucp> <15104@smoke.brl.mil> Sender: news@travis.csd.harris.com Organization: Harris Computers Systems Division, Fort Lauderdale,FL Lines: 49 In article <15104@smoke.brl.mil> gwyn@smoke.brl.mil (Doug Gwyn) writes: >In article <1991Feb6.053237.11051@iguana.uucp> merce@iguana.uucp (Jim Mercer) writes: >>is my popen() broken? > >No, because popen() DID successfully start up "sh -c no_such_file"; >when you examine the status from pclose() you should see that the >command did not succeed, however. This is quite correct. However, in many cases it is important to know if the pipe was succesfully opened before attempting to write to it. In such cases, you may want to catch the SIGPIPE signal (which occurs when a pipe is broken). Youll need to write a test character to the pipe, and then flush it, before seeing if your pipe fails. Something like the following should work: FILE *pipe_fp; int (*broken_pipe_handler)(); . . . signal( SIGPIPE, broken_pipe_handler ); pipe_fp = popen( program_name, "w" ); if ( !pipe_fp ) { perror( "popen failed" ); exit( 1 ); } else { fputc( '\n', pipe_fp ); /* use newline as the test-character */ fflush( pipe_fp ); signal( SIGPIPE, SIG_IGN ); /* if we get here, assume it's alright * to reset the default SIGPIPE handler * (this may or may not be safe to do). */ } . . . If anyone would like, I have an example of such code that uses popen to open a pager (such as "less"). If the pipe is broken, it tries to use "more" and if all else fails, then it just uses stdout. Other solutions are welcome!!! Oh yeah - this is all Unix-specific of course! ______________________ "And miles to go before I sleep." ______________________ Brad Appleton brad@ssd.csd.harris.com Harris Computer Systems uunet!hcx1!brad Fort Lauderdale, FL USA ~~~~~~~~~~~~~~~~~~~~ Disclaimer: I said it, not my company! ~~~~~~~~~~~~~~~~~~~