0

Consider the following 2 lines of code

sprintf(comm, "cat %s.bz2 | bunzip2 -dc", string);  
fp = popen(comm, "r");

If I am opening a file and the file doesn't exist, I will simply get a NULL file. However if I use popen to pipe a file through bunzip2, if the underlying file doesn't exist, or is corrupt, then fp will have a valid pointer and not NULL. The obvious way to check would seem to be to check the exit status of the command run by popen, but this doesn't seem possible.

Is there an easy way to make popen return null if a command fails?

alk
  • 69,737
  • 10
  • 105
  • 255
camelccc
  • 2,847
  • 8
  • 26
  • 52
  • 2
    You should not commit UUoC ([Useless Use of `cat`](https://stackoverflow.com/questions/11710552/useless-use-of-cat)); you should be using: `sprintf(comm, "bunzip2 -dc %s.bz2", string);`. At one level, for small files (say files less than a gigabyte in size), it probably doesn't matter. If you're dealing with large files, it does affect the performance — you're making an extra copy of the data in the file unnecessarily. – Jonathan Leffler Jul 20 '19 at 13:32
  • 1
    If you want to read the contents of a bzip2-compressed file, you can just use the `` stdio-like API directly (`BZ2_bzopen()`, `BZ2_bzread()`, etc.) instead of messing with `popen()`. – Shawn Jul 20 '19 at 13:42
  • The source code to @Shawn's comment is here: https://sourceware.org/bzip2/downloads.html – alk Jul 20 '19 at 13:45

1 Answers1

3

is there an easy way to make popen return null if a command fails?

No.

It isn't popen()'s task to decide if a command it successfully ran (that is: started) failed. If a command is taken to have "failed" completely depends on the logical application level context it is run in/under.

Still, if popen() did not return NULL it requires a related call to pclose(). The result of this latter call tells you the exit-status of what had been run by popen(). Using this exit-status the calling program can take any decision how to interpret the outcome of popen(), from success to failure.

alk
  • 69,737
  • 10
  • 105
  • 255