Monday, March 11, 2013

Run Applications Through C Program

Some times our project demands to start a particular application through C program. Here i will show you how to do that.

To start a application through C program, we can use a system call called execlp, which comes under exec family of UNIX system calls.

// Compiler: GCC
//File Name: execute.c
#include <stdio .h>
#include <unistd .h>
void main()
{
pid_t pid = fork();
switch (pid) {
       case 0:
        execlp("/bin/sh", "sh", "-c", "firefox http://umencs.blogspot.in", NULL);
            //execlp("/bin/sh", "sh", "-c", "gedit", NULL);
            //execlp("/bin/sh", "sh", "-c", "nautilus", NULL);
       case -1:
        printf("Error: can't execute command: fork() failed\n");
       }
}

In execlp system call -c option is used to read commands from the command_string operand instead of from the standard input.

To run above program use following commands
$gcc execute.c
$./a.out

the above program will open  http://umencs.blogspot.in in Firefox.


2 comments:

  1. http://stackoverflow.com/questions/1697440/difference-between-system-and-exec-in-linux

    ReplyDelete