Monday, 23 December 2013

Executing shell commands using C


We Can Use system() function to execute a command

        #include <stdlib.h>
        int system(const char *command);

Small Example Code Snipet

int main(int argc, char *argv[]){
        const char *command = "ls";
        system(command);
        return 0;
}
system() executes a command specified in command by calling /bin/sh -c command, and returns after the command has been completed.
During execution of the command, SIGCHLD will be blocked, and SIGINT and SIGQUIT will be ignored.

A Complete Program.

QUESTION::
Write a C program to take set of commands separated by semicolons(;).
Execute each commands sequentially and wait till excution of commands over.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void executeCommand(const char *command)
{
        printf("\n=====================\n");
        system(command);
        printf("=====================\n");
}

int main(int argc, char *argv[]){
        char commands[1024];
        char *tempPos, *itrCommand;
        char command[256];
        int i;
        if(argc > 1)
        {
                memset(commands,0x00,sizeof(commands));
                for(i=1;i<argc;i++)
                {
                        strcat(commands,argv[i]);
                }
        }else{
                memset(commands,0x00,sizeof(commands));
                printf("Enter Commands Separated By Semicolon.\n");
                scanf(" %[^\n]s",commands);
        }
        printf("commands : %s\n",commands);
        itrCommand = commands;
        while(tempPos = strchr(itrCommand,';')){
                (*tempPos)=0x00;
                memset(command,0x00,sizeof(command));
                strcpy(command,itrCommand);
                executeCommand(command);
                itrCommand = tempPos+1;
                tempPos = NULL;
        }
        if((*itrCommand)!=0x00)
        {
                memset(command,0x00,sizeof(command));
                strcpy(command,itrCommand);
                executeCommand(command);
        }
        return 0;
}

Compilation and Excution In Linux System

rajesh@ubuntu:~/rajesh/Linux$ gcc system.c -o exe_using_C
rajesh@ubuntu:~/rajesh/Linux$ ./exe_using_C
Enter Commands Separated By Semicolon.
echo Rajesh;ls
commands : echo Rajesh;ls

=====================
Rajesh
=====================

=====================
a.out  executing.txt  exe_using_C  system.c
=====================
rajesh@ubuntu:~/rajesh/Linux$

No comments:

Post a Comment