Friday, 8 May 2015

Fork() and wait() 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 ()
{
  int child_status;
  char* arg_list[] = { "ls",  "-l",  "/",  NULL  };
   spawn("ls", arg_list);
  wait (&child_status);
  return 0;
}

Output:
 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 17 15:33 dev
drwxr-xr-x  93 root root 12288 Mar 17 15:33 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 17 15:32 misc
drwxr-xr-x   2 root root  4096 Oct 11  2006 mnt

drwxr-xr-x   2 root root     0 Mar 17 15:32 net

No comments:

Post a Comment