fork-with-exec.c - fork-with-exec.c example showing how to create a new(child process then use execlp to execute a command in the

fork-with-exec.c - fork-with-exec.c example showing how to...

This preview shows page 1 - 2 out of 2 pages.

/* fork-with-exec.c */ /* example showing how to create a new (child) process, */ /* then use execlp() to execute a command in the child */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> int main() { pid_t pid; /* process id (unsigned int) */ pid = fork(); /* create a child process */ if ( pid == -1 ) /* fork could fail: not enough memory for child process */ { /* (can also set a sysadmin limit as to how many procs) */ perror( "fork() failed" ); return EXIT_FAILURE; } if ( pid == 0 ) /* note that 0 is the mechanism for us to know we are in the child */ { printf( "CHILD: my pid is %d\n", getpid() ); printf( "CHILD: Execute a command ..... \n" ); /* execute the /bin/ls program in this child process: */ int rc = execlp( "/bin/ls", "ls", "-l", NULL ); /* ^^^^^^^ ^^ ^^ path of command,
Image of page 1
Image of page 2

You've reached the end of your free preview.

Want to read both pages?

  • Fall '08
  • INGALLS
  • Operating Systems, Exit, Parent process, Child process, */

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture