2

How should I check if the system command was run successfully and it didn't return error? According to MSDN Library, there are multiple cases. I couldn't be sure if the following snippet is correct.

char buffer[100];
int ret_val;
strcpy(buffer, "copy *.txt ");
strcat(buffer, path);
ret_val = system(buffer);
if(0 != ret_val)
{
  perror("There was an error");
}
else
{
  printf("The command was run successfully.");
}

Return Value

If command is NULL and the command interpreter is found, returns a nonzero value. If the command interpreter is not found, returns 0 and sets errno to ENOENT. If command is not NULL, system returns the value that is returned by the command interpreter. It returns the value 0 only if the command interpreter returns the value 0. A return value of – 1 indicates an error, and errno is set to one of the following values:

2

2 Answers 2

1

To catch all the cases, you also need to check errno, like the documentation states:

if (ret_val == 0 && errno == 0)
{
  printf("success!\n");
}

Make sure you also clear errno just before calling system().

4
  • it's not really working. I put a file it can not delete and run as you suggested. In the Autos window of Visual Studio 2008, I see "_errno returned 0x00400808". But it goes into this if statement too. :(
    – mustafa
    Jan 20, 2012 at 14:13
  • man 3 system says: RETURN VALUE The value returned is -1 on error (e.g. fork() failed), and the return status of the command otherwise. This latter return status is in the format specified in wait(2). Thus, the exit code of the command will be WEXITSTATUS(status). In case /bin/sh could not be executed, the exit status will be that of a command that does exit(127). Jan 20, 2012 at 14:17
  • 1
    @Pete Wilson and for Windows?
    – mustafa
    Jan 20, 2012 at 14:25
  • @mustafa -- Beats me. What did google turn up for you? What did you find on msdn? Jan 20, 2012 at 15:59
0

Since the argument to system is not NULL, you concentrate on that case which is a very simple one: -1 is the system function fails, and otherwise the return code of the actual command.

3
  • I saw that system was returning 1 in some cases.
    – mustafa
    Jan 20, 2012 at 14:05
  • @mustafa Then it's the actual command (copy in your case) that exits with that return code. Jan 20, 2012 at 14:08
  • yes, it may be. I created a file it can not delete. on the console it outputs "The process cannot access the file because it is being used by another process." but system is still returning 0
    – mustafa
    Jan 20, 2012 at 14:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.