user8240105
user8240105

Reputation:

how to get status in c for system() commands

I want to get the status of command which i passed as a parameter to the system() function. suppose i pass "attrib +h E:/songs/lovingsong.mp3" as system("attrib +h E:/songs/lovingsong.mp3") since i know that the path give by me is not right , i.e there is no such folder songs in my E: drive so on console it says path not found. How can i get "path not found" message in my c program or any status code ,so that i can know the command did not work.

/* system example : DIR */
#include <stdio.h>      /* printf */
#include <stdlib.h>     /* system, NULL, EXIT_FAILURE */

int main ()
{
  int i;
  printf ("Checking if processor is available...");
  if (system(NULL)) puts ("Ok");
    else exit (EXIT_FAILURE);
  printf ("Executing command DIR...\n");
  i = system ("attrib +h E:/songs/lovingsong.mp3");
  //want to get status here
  printf ("The value returned was: %d.\n",i);
  return 0;
}

Upvotes: 0

Views: 1366

Answers (1)

Notice that the C11 standard (read n1570) defines system in §7.22.4.8 (with its formal argument being called string below):

If string is a null pointer, the system function determines whether the host environment has a command processor. If string is not a null pointer, the system function passes the string pointed to by string to that command processor to be executed in a manner which the implementation shall document; this might then cause the program calling system to behave in a non-conforming manner or to terminate

So there is no clear definition, according to the C11 standard, of what system does. You need to dive into the documentation of your particular C11 implementation.

On POSIX (e.g. Linux or MacOSX), system is required to run the POSIX shell /bin/sh with the -c argument followed by the string and there is a complex chapter describing what is a POSIX shell.

Perhaps you want to pass a command which is redirecting the stderr of attrib to stdout, and read that stdout produced by your attrib command. On POSIX you could use popen (with pclose) for that purpose. Maybe (and probably) your implementation has something similar: _popen. And you also need to read the documentation of your attrib command.

So your question is really operating system specific. You need to dive into the documentation of your particular operating system.

And you might simply test (before running system) that the file E:/songs/lovingsong.mp3 exists. Maybe use _access (with perhaps a race condition if that file gets removed before running attrib).

Be also aware of the $PATH variable.

PS. I don't know anything about Windows, but you did not tag your question with Windows.

Upvotes: 1

Related Questions