ch3-wait
Chapter_3 term-spawn | zombie |
fork-exec.c ALP, p. 59-60
#include <stdio.h> // for printf(), fprintf(), stderr, NULL
#include <stdlib.h> // for abort(), WIFEXITED(), WEXITSTATUS()
#include <sys/types.h> // for pid_t
#include <unistd.h> // for fork(), execvp()
#include <wait.h> // wait.h includes sys/wait.h,
// full path /usr/include/x86_64-linux-gnu/sys/wait.h,
// which defines wait(), WIFEXITED(), WEXITSTATUS()
int spawn (char * program, char ** arg_list);
// Spawn a child process running a new program
int main()
{
int child_status;
/* The argument list to pass to the `ls' command: */
char * arg_list[] =
{
"ls", /* argv[0], the name of the program */
"-l", // long listing
// "/", // root directory
NULL /* The argument list must end with a NULL */
};
/* Spawn a child process running the "ls" command: */
spawn ("ls", arg_list); // ignore child ID return value
printf ("Done with main program\n");
/* Wait for the child process to complete: */
wait (&child_status); // wait() exits when any child finishes
if (WIFEXITED (child_status))
{
printf ("Child process exited normally, with exit code %d\n",
WEXITSTATUS (child_status));
}
else {printf ("The child process exited abnormally\n");}
return 0;
}
int spawn (char * program, char ** arg_list)
{
pid_t child_pid;
child_pid = fork(); /* Duplicate this process */
if (child_pid != 0) /* This is the parent process. */
{return child_pid;} // the returned value is ignored in main()
else // child process
{ /* Now execute `program', searching for it in the path: */
execvp (program, arg_list);
/* The execvp() function returns only if an error occurs: */
fprintf (stderr, "An error occurred in execvp()\n");
abort(); // end program
}
}
/*
gcc fork-exec.c -o fork-exec
./fork-exec
Done with main program
total 24
-rwxrwxr-x 1 user user 17088 Sep 16 09:07 fork-exec
-rw-rw-r-- 1 user user 1728 Sep 16 09:07 fork-exec.c
Child process exited normally, with exit code 0
*/
Chapter_3 term-spawn | BACK_TO_TOP | zombie |
Comments
Post a Comment