Friday, 8 May 2015

fork() & execvp() UNIX System Call

#include  <stdio.h>
#include  <stdlib.h>
#include  <sys/types.h>

int spawn (char* program, char** arg_list)
{
  pid_t child_pid;
  child_pid = fork ();
  if (child_pid != 0)
          return child_pid;
  else {
     execvp (program, arg_list);    
     fprintf (stderr,"an error occurred in execvp\n");
     abort ();
  }
}
int main ()
{
   char* arg_list[] = { "ls", "-l", "/", NULL  };
   spawn ("ls", arg_list);
  printf ("done with main program\n");
  return 0;

 }


Output:
  
[telnet17@linux ~]$  ./a.out
done with main program
[telnet17@linux ~]$ total 138
drwxr-xr-x   2 root root  4096 Sep 12  2009 bin
drwxr-xr-x   4 root root  1024 Sep 12  2009 boot
drwxr-xr-x  11 root root  3620 Mar 16 19:16 dev
drwxr-xr-x  93 root root 12288 Mar 16 19:16 etc
drwxr-xr-x 115 root root  4096 Feb  9 20:26 home
drwxr-xr-x  14 root root  4096 Sep 12  2009 lib
drwx------   2 root root 16384 Sep 12  2009 lost+found
drwxr-xr-x   2 root root  4096 Sep 12  2009 media
drwxr-xr-x   2 root root     0 Mar 16 19:16 misc
drwxr-xr-x   2 root root  4096 Oct 11  2006 mnt
drwxr-xr-x   2 root root     0 Mar 16 19:16 net
drwxr-xr-x   2 root root  4096 Oct 11  2006 opt

No comments:

Post a Comment