ch3-spawn

Chapter_3     fork SIGUSR1







fork-exec.c     ALP, p. 54-55


#include <stdio.h> // for printf(), fprintf(), stderr, NULL
#include <stdlib.h> // for abort()
#include <sys/types.h> // for pid_t
#include <unistd.h> // for fork(), execvp()

int spawn (char * program, char ** arg_list);
// Spawn a child process running a new program
int main()
{
/* 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 the returned child process ID
printf ("Done with main program\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 17000 Sep 15 23:41 fork-exec
-rw-rw-r-- 1 user user 2504 Sep 15 23:42 fork-exec.c
// Ctrl^C
*/




Note:  See also term-spawn and wait.









Chapter_3     fork BACK_TO_TOP SIGUSR1



Comments

Popular posts from this blog

Contents