在C中的系统命令内执行linux命令的成功/失败

时间:2015-08-17 09:11:57

标签: c linux

我正在尝试在C system()函数中执行linux tar命令。它是这样的:

if (-1 == system("tar -xf files.tar.gz file1")) {
    printf("tar failed\n");
}

如果“files.tar.gz”中没有“file1”,则程序不会打印“tar failed”。如何识别system()内部执行的命令是否失败?

2 个答案:

答案 0 :(得分:2)

来自here

  

如果command不是空指针,则返回的值取决于   系统和库实现,但通常是预期的   被调用命令返回的状态代码(如果支持)。

在Linux上,程序通常在成功时返回零退出状态,在失败时返回另一个值。您可以尝试检查非零值,而不是检查特定的退出状态-1

if (system("echo hi"))
    printf("In C a non-zero value is treated as true\n");

当我使用有效的输入文件在我的系统上运行tar时,我可以通过以下方式检查返回状态:

# echo With a valid input file
# tar -cf test.tar test.py
# echo $?
0
# echo with an invalid input file
# tar -cf test.tar t
tar: t: Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors
# echo $?
2

此处tar在失败时返回退出状态2

使用以下程序,我可以打印错误状态:

int main(int argc, char** argv)
{
  printf("%i\n", system("tar -cf test.tar test.py"));   /// Outputs 0
  printf("%i\n", system("tar -cf test.tar bad"));   /// Outputs 512

  int err;
  if ((err = system("tar -cf test.tar test.py")))
  {
      printf("There was an error (%i)\n", err);
      return 1;
  }

  return 0;
}

输出0的那个成功而另一个失败。当我从bash和我的C程序中调用tar时,我不知道为什么错误状态不同。

答案 1 :(得分:-2)

您可能无法获得所需输出的原因是因为拼写错误。您的代码应更改为

if (-1 == system("tar -xf files.tar.gz file1")) {
    printf("tar failed\n");
}

你错过了)