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.

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
int main (int argc, char * argv[])
{
  char * cmd_line;
  char * arg;
10    int index;
11    int len;
12    int ret = -1;
13    if (argc > 1)
14    {
15      index = 1;
16      while (arg = argv [index])
17      {
18        len += strlen (arg);
19        len ++;
20        index ++;
21      }
22      cmd_line = (char *) calloc (1, len);
23      if (cmd_line == NULL)
24      {
25          perror ("memory allocation error!\n");
26          return -1;
27      }
28      index = 1;
29      while (arg = argv [index])
30      {
31        index ++;
32        strcat (cmd_line, arg);
33        if (argv [index])
34        {
35          strcat (cmd_line," ");
36        }
37      }
38      ret = system (cmd_line);
39      free (cmd_line);
40      return ret;
41    }
42    else
43    {
44      printf ("At least one argument needed.\n");
45      printf ("Syntax: redo \n");
46      return -1;
47    }
48  }
49 

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
$

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

 Vote 0

Similar topics related to this section

Radix Sort, argc and argv, C startup routine, argv environ getenv, system(), atexit, raise signal, abort exit,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan