60 likes | 186 Views
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
E N D
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 • 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
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[]);
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.
#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; }