Gillespie
Gillespie

Reputation: 6561

system() returns non-zero but still performs action

I'm using the system command to gzip some log files:

if (system("gzip -f log.csv"))
{
      printf("gzip failed");
      return;  
}

Occasionally (very inconsistently), I'll get a gzip failed message, which exits the function and doesn't perform some other tasks that are contingent on the gzip being successful. When I go examine the directory at the command-line, however, the file was indeed gzipped correctly into log.csv.gz (i.e. I can gunzip it -- the command apparently did not fail even though system returned a non-zero value).

How is this possible? Am I just missing something?

Upvotes: 0

Views: 607

Answers (3)

Gillespie
Gillespie

Reputation: 6561

I did a little more investigation, and it appears that the root cause of the gzip failures seemed to be a race condition between two waidpid calls: the one in system() itself, and the other in a custom SIGCHLD handler that somewhere else in the code (this is a huge multi-thousand line process).

If the child (gzip) is harvested by the custom SIGCHLD handler, then system() returns -1 (since its waidpid fails), otherwise system() returns 0 as expected.

This is the SO post that helped me ultimately solve it:

C++: system(0) Returns 0

Upvotes: 1

Joseph Young
Joseph Young

Reputation: 2795

According to this guide, gzip returning with an exit code of 2 means it had a warning. This means it probably produced an output but maybe not correctly?

Upvotes: 4

Charles Duffy
Charles Duffy

Reputation: 295308

There is absolutely no requirement that a program with a nonzero exit status roll back all actions it performed prior to the error resulting in that status. In fact, such an action would often be either impossible or destructive.

As such, it is entirely possible for any command to return a nonzero exit status but still to have an effect on system state.

Upvotes: 3

Related Questions