System() function in c

C runtime library has an interesting function called system() to invoke commands in the shell. It takes commands and arguments in a string separated by spaces. We generally call fork() and then execxx() to spawn a new process. It does same and hopefully wraps those calls inside it. It also makes calling interface simpler and easy to use. We have next example to elaborate this.

System() function Description

The C library function int system(const char *command) is used to create a child process. A string containing the command name or program name followed by the arguments are passed to the function. This simple but effective function can be used to execute any command like pause, cls, echo etc.

System() - Declaration

Following is the declaration for system() function.

 int system(const char *command);   

System() - Parameters

command − This is the C string containing the command.

System() - Return Value

The value returned is -1 on error, and the return status of the child command otherwise.

System function in c example


#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
int main (int argc, char * argv[])
{
  char * cmd_line;
  char * arg;
  int index;
  int len;
  int ret = -1;
  if (argc > 1)
  {
    index = 1;
    while (arg = argv [index])
    {
      len += strlen (arg);
      len ++;
      index ++;
    }
    cmd_line = (char *) calloc (1, len);
    if (cmd_line == NULL)
    {
        perror ("memory allocation error!\n");
        return -1;
    }
    index = 1;
    while (arg = argv [index])
    {
      index ++;
      strcat (cmd_line, arg);
      if (argv [index])
      {
        strcat (cmd_line," ");
      }
    }
    ret = system (cmd_line);
    free (cmd_line);
    return ret;
  }
  else
  {
    printf ("At least one argument needed.\n");
    printf ("Syntax: redo \n");
    return -1;
  }
}

Output:


$ ./redo ls -l redo.c
-rw-r--r-- 1 user root 771 Jul 15 14:07 redo.c
$
$ ./redo uname -a
Linux home 2.6.18-164.10.1 #1 SMP Mon May 3 17:50:00 PDT 2010 x86_64 GNU/Linux
$
$ ./redo ./redo
At least one argument needed.
Syntax: redo <args>
$ ./redo ./redo abcd
sh: abcd: command not found
$

About our authors: Team EQA

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

#