简体   繁体   English

从C程序中的linux命令获取返回码

[英]Get return code from linux command in C program

I am basically trying to check if a particular file exists or not. 我基本上是在尝试检查特定文件是否存在。 For that I am using the test command of Unix. 为此,我使用了Unix的test命令。

 sprintf(execbuf, "%s if test -r %s ; then true; else exit; fi;",
         execbuf, st->file, NO_FILE);

It works fine, but I do not want to exit if the file is not here, rather it should return FAIL. 它工作正常,但是如果文件不在此处,我不想退出,而是应该返回FAIL。

I am not able to figure out how to make the program return FAIL. 我不知道如何使程序返回失败。 I was thinking of using the exit code from the above command, but still I am not able to figure out how to use that exit code outside the Linux command in the program. 我当时正在考虑使用上述命令中的退出代码,但仍然无法弄清楚如何在程序中的Linux命令之外使用该退出代码。

I'd recommend you rather just use the access () call, and not execute external shell commands to figure this out. 我建议您宁可只使用access ()调用,也不要执行外部shell命令来解决此问题。

Just be aware that such cases are subject to race conditions - the file might exist when you call access() (or execute a shell command that determines whether the file exists), but it might be gone when you actually need it later on. 请注意,这种情况受竞争条件的影响-调用access()时该文件可能存在(或执行确定该文件是否存在的shell命令),但是稍后您实际需要它时,该文件可能会消失。 If that's a problem for you, just open() the file, and use the file descriptor later on when you actually need it for I/O. 如果这对您来说是个问题,只需打开()文件,然后在以后实际需要I / O时使用文件描述符。

If you're not married to what your doing right now, then I'd suggest using stat: 如果您不喜欢现在的工作,那么建议您使用stat:

#include <sys/stat.h>
#include <stdio.h>

int main (int argc, char** argv[])
{
  struct stat sts;
  if (stat(argv[1], &sts) == -1 && errno == ENOENT)
      printf ("The file %s doesn't exist...\n", argv [1]);
  else
      printf("The file exists\n");

This will tell you if it exists or not. 这将告诉您它是否存在。 If you dont' want to pass it command line, parameter 1 is a const char*, so just pass it the file name. 如果您不想通过命令行,则参数1是const char *,因此只需将文件名传递给它即可。

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

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