简体   繁体   English

system()返回非零值,但仍执行操作

[英]system() returns non-zero but still performs action

I'm using the system command to gzip some log files: 我正在使用system命令gzip一些日志文件:

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. 偶尔(非常不一致),我会收到一条gzip failed消息,该消息会退出该函数,并且不会执行其他某些取决于gzip成功的任务。 When I go examine the directory at the command-line, however, the file was indeed gzipped correctly into log.csv.gz (ie I can gunzip it -- the command apparently did not fail even though system returned a non-zero value). 当我去检查,在命令行的目录,但该文件确实正确gzip压缩到log.csv.gz (即我可以gunzip它-命令显然,即使没有失败system返回非零值) 。

How is this possible? 这怎么可能? Am I just missing something? 我只是想念什么吗?

According to this guide , gzip returning with an exit code of 2 means it had a warning. 根据该指南 ,gzip返回退出代码为2表示它已发出警告。 This means it probably produced an output but maybe not correctly? 这意味着它可能产生了输出,但可能不正确?

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. 这样,任何命令完全有可能返回非零退出状态,但仍然会影响系统状态。

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). 我做了一些进一步的调查,看来gzip失败的根本原因似乎是两个waidpid调用之间的竞争状态:一个在system()本身,另一个在自定义SIGCHLD处理程序中,在其他地方代码(这是一个巨大的数千行过程)。

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. 如果子项(gzip)由自定义SIGCHLD处理程序收集,则system()返回-1(因为它的waidpid失败),否则system()返回预期的0。

This is the SO post that helped me ultimately solve it: 这是帮助我最终解决它的SO帖子:

C++: system(0) Returns 0 C ++:system(0)返回0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM