Sunday, March 11, 2012

Program using EXECLP() System Call




Ex. No.: 4(c)
Program using EXECLP() System Call


AIM:
               Write a C program using execlp system call  
 
execlp: This system call is used by one of the processes(parent or child) to replace the process’s memory space with a new memory image of the program containing the execlp system call and starts its execution.
 
Syntax:
int execlp(const char *file, const char *arg, ...);
          The functions execlp will duplicate the actions of the shell in searching for an executable file if the specified file name does not contain a slash (/) character. The search path is the path specified in the environment by the PATH variable. If this variable isn't specified, the default path ``:/bin:/usr/bin'' is used. In addition, certain errors are treated specially.

Return value

If any of the execlp functions returns, an error will have occurred. The return value is -1, and the global variable errno will be set to indicate the error. 
 
#include<stdlib.h>
#include<ctype.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
 
int main (int argc,char *a[])
{
  pid_t child_pid;
  int choice;
  printf("\nOptions :\n1.Date\n2.ls\n3.File Type");
  printf("\n4.Word count\n5.Users\n6.Exit\n");
  printf("Enter ur choice :");
  scanf("%d",&choice);
  child_pid = fork();
  if (child_pid == 0)
   {
     printf("\nChild Process:\n");
     switch(choice)
     {
       case 1:
         printf("\n");
         execlp("date","date",NULL);
         break;
       case 2:
         printf("\n");
         execlp("ls","ls",NULL);
         break;
       case 3:
         printf("\n");
         execlp("file","file","hello",NULL);
         break;
       case 4:
         printf("\n");
         execlp("wc","wc","hello",NULL);
         break;
       case 5:
         printf("\n");
         execlp("who","who",NULL);
         break;
       default:
         break;
     }
     printf("\nChild process terminated:\n");
   }
  return 0;
}
 
Output :
[cs281016@linux]$cc execlp.c
[cs281016@linux]$ ./a.out execlp.c
 
Options :
1.Date
2.ls
3.File Type
4.Word count
5.Users
6.Exit
Enter ur choice :1
 
Child Process:
 
Tue Aug  9 01:24:37 IST 2005
 
Options :
1.Date
2.ls
3.File Type
4.Word count
5.Users
6.Exit
Enter ur choice :2
 
Child Process:
a.out  cp.c        execvp.c    forkk.c   pri.c    
bg     disp.c      execvp.out  fork.out  priority.c  
big    execlp.c    fibo        hello     round1.c  
count  execlp.out  fork.c      odd       round1.c  
Options :
1.Date
2.ls
3.File Type
4.Word count
5.Users
6.Exit
Enter ur choice :3
 
Child Process:
 
hello: ASCII text
 
Options :
1.Date
2.ls
3.File Type
4.Word count
5.Users
6.Exit
Enter ur choice :4
 
Child Process:
 
4       7      41 hello
 
Options :
1.Date
2.ls
3.File Type
4.Word count
5.Users
6.Exit
Enter ur choice :6
 
Child Process:
 
Child process terminated.

 
Result:

  Thus a C program is implemented using execlp system call.

No comments:

Post a Comment