ch3-term-spawn
Chapter_3 SIGUSR1 | wait |
fork-exec.c ALP, p. 54-55, 58
#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(), sleep()
#include <signal.h> // for kill(), SIGTERM
// signal.h includes bits/signum.h, which includes
// bits/signum-generic.h, which defines SIGTERM:
// /usr/include/x86_64-linux-gnu/bits/signum-generic.h:
// #define SIGTERM 15 /* Termination request. */
int spawn (char * program, char ** arg_list);
// Spawn a child process running a new program
int main()
{
pid_t childid;
/* 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: */
childid = spawn ("ls", arg_list);
printf ("SIGTERM = %d\n", SIGTERM);
printf ("Done with main program\n");
sleep(1); // wait for child to finish
kill (childid, SIGTERM);
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
SIGTERM = 15
Done with main program
total 24
-rwxrwxr-x 1 user user 17128 Sep 16 08:17 fork-exec
-rw-rw-r-- 1 user user 1764 Sep 16 08:17 fork-exec.c
*/
Chapter_3 SIGUSR1 | BACK_TO_TOP | wait |
Comments
Post a Comment