Thursday, March 8, 2012

How to call shell script program in C language program [ system(./xxxx.sh) ]

How to call shell script program in C language program [ system(./xxxx.sh) ]

Example :
In the same directory :

showMenu.sh
showMenu.c


showMenu.sh


#! /bin/sh
# Script to create simple menus and take action according to that selected
# menu item
#
while true
do
clear
  echo "-------------------------------------"
  echo " Main Menu "
  echo "-------------------------------------"
  echo "[1] Show Todays date/time"
  echo "[2] Show files in current directory"
  echo "[3] Show calendar"
  echo "[4] Show all socket man pages"
  echo "[5] Select this choice for submit"
  echo "[6] Exit/Stop"
  echo "======================="
  echo -n "Enter your menu choice [1-6]: "
  read yourch
  case $yourch in
    1) echo "Today is `date` , press a key. . ." ; read ;;
    2) echo "Files in `pwd`" ; ls -l ; echo "Press a key. . ." ; read ;;
    3) cal ; echo "Press a key. . ." ; read ;;
    4) man -k socket ; echo "Press a key. . ." ; read ;;
    5) echo -n "Enter your student ID : "; read id ;
      tar cvfz $id.tar.gz *.*
      mail -s $id -a $id.tar.gz twatchai.informatics@gmail.com < .; echo "Press a   key. . ." ; read ;; 6) exit 0 ;; *) echo "Opps!!! Please select choice 1,2,3,4,5, or  6"; 

     echo "Press a key. . ." ; read ;; 
  esac 
done

showMenu.c


#include <stdio.h>
#include <stdlib.h>

int main()
{
   system("./showMenu.sh");
   exit(EXIT_SUCCESS);
}



Compile showMenu.c
$gcc showMenu.c -o showMenu.o

showMenu.c   showMenu.o   showMenu.sh

Run execute showMenu.sh
$./showMenu.o
-------------------------------------
 Main Menu
-------------------------------------
[1] Show Todays date/time
[2] Show files in current directory
[3] Show calendar
[4] Show all socket man pages
[5] Select this choice for submit
[6] Exit/Stop
=======================
Enter your menu choice [1-6]:


No comments:

Post a Comment