1) fork() system call duplicate self process image.
Parent process branch child process and receive child process ID.
2) Parent process wait child process ending.
Parent process call wait() while child process doing.
System call wait() retrieve child process exit code.
Parent process can judge child process result.
3) Child process image replace the new image.
Current image replace /usr/bin/printf image by execl() in this examle.
execl("/usx/bin/printf", "printf", "Name=%s\\nAge=%d\\n", "Tanaka", "36", NULL);
--> "printf" is an example, You can execute favorite program.
If child process fail replacing, when error exit.
Program compiling.
$ gcc fork-exec.c -o fork-exec
Program running.
$ ./fork-exec
Name=Tanaka
Age=36
Child process was normal end.
Chid process exec() can send return code, but it was limited 8bit size.
If you see behavior child process exit, when you try below code changing.
1) Running program(/usr/bin/printf) error exit.
Change line 47, execl() parameters 5 “36” --> “ABC”
$ ./fork-exec
Name=Tanaka
Age=printf: ABC: expected a numeric value
0
Error handling example 1.[1]
2) Current image replacing error.(execl() error)
Change line 47, execl() parameter 1 "/usr/bin/printf" --> "/usx/bin/printf"
$ ./fork-exec
execl(): No such file or directory
Error handling example 2.[2]
Child process fail execl() when use _exec(). What does exec() differ at _exec()?
You can read Linux man _EXIT(2) NOTES.
The function _exit() is like exit(3), but does not call any functions registered with atexit() or on_exit().
fork-exec.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> static pid_t childID; int main(int argc, char** argv) { if((childID = fork()) < 0 ) { perror("fork()"); exit(-1); } else { if(childID != 0) { // Parent process int status, ret; waitpid(childID, &status, 0); if(WIFEXITED(status)) { ret = WEXITSTATUS(status); if(ret != 0) { // If you require child process exit code, // You can write judgement code. // Child process exit status was limited 8bit. // For example. // ret = WEXITSTATUS(status); if(ret == 1) { // You can take 00H-FFH // You code. printf("Error handling example 1.[%d]\n", ret); } else { printf("Error handling example 2.[%d]\n", ret); } } else { printf("Child process was normal end.\n"); } } else { printf("Child process was fail stopped.\n"); // ex. Segmentation Failt } } else { // Child process execl("/usr/bin/printf", "printf", "Name=%s\\nAge=%d\\n", "Tanaka", "36", NULL); perror("execl()"); _exit(2); } } return(0); }
No comments:
Post a Comment