简体   繁体   中英

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.

 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.

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.

I'd recommend you rather just use the access () call, and not execute external shell commands to figure this out.

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. 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.

If you're not married to what your doing right now, then I'd suggest using 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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