mustafa
mustafa

Reputation: 3905

how to check system() result

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:

Upvotes: 2

Views: 6329

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409482

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.

Upvotes: 0

unwind
unwind

Reputation: 400129

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

Upvotes: 1

Related Questions