1 / 6

CPS4200

CPS4200. Unix Systems Programming Chapter 3-2 Process in UNIX. The exec Function. Use fork function to create a copy of the calling process; Then require the child process to execute code that is different from parent. The exec Function. exec

lundy
Download Presentation

CPS4200

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CPS4200 Unix Systems Programming Chapter 3-2 Process in UNIX

  2. The exec Function • Use fork function to create a copy of the calling process; • Then require the child process to execute code that is different from parent.

  3. The exec Function exec • Exec provide a facility for overlaying the process image of the calling processing with a new image. • Parent continues to execute the original code and child execute the new program fork-exec pair

  4. The exec Function #include <unistd.h> extern char **environ; int execl(const char *path, const char *arg0, ... /*, char *(0) */); int execle (const char *path, const char *arg0, ... /*, char *(0), char *const envp[] */); int execlp (const char *file, const char *arg0, ... /*, char *(0) */); int execv(const char *path, char *const argv[]); int execve (const char *path, char *const argv[], char *const envp[]); int execvp (const char *file, char *const argv[]);

  5. The exec Function • The execl forms take a variable number of parameters with a NULL-terminated list of command line arguments. • The execv forms take an argv array which can be created with makeargv. • The argi parameter represents a pointer to a string, and argv and envp represent NULL-terminated array of pointers to strings. • The p forms use the PATH environment variable to search for the executable. • The e forms allow you to set the environment of the new process rather than inheriting it from the calling process.

  6. #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> int main(void) { pid_t childpid; childpid = fork(); if (childpid == -1) { perror("Failed to fork"); return 1; } if (childpid == 0) { /* child code */ execl("/bin/ls", “ls", "-l", NULL); perror("Child failed to exec ls"); return 1; } if (childpid != wait(NULL)) { /* parent code */ perror("Parent failed to wait due to signal or error"); return 1; } return 0; }

More Related