Debian Codegraph @

listings/chapter-3/fork-exec.c

raw
1 /***********************************************************************
2 * Code listing from "Advanced Linux Programming," by CodeSourcery LLC *
3 * Copyright (C) 2001 by New Riders Publishing *
4 * See COPYRIGHT for license information. *
5 ***********************************************************************/
6
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <sys/types.h>
10 #include <unistd.h>
11
12 /* Spawn a child process running a new program. PROGRAM is the name
13 of the program to run; the path will be searched for this program.
14 ARG_LIST is a NULL-terminated list of character strings to be
15 passed as the program's argument list. Returns the process id of
16 the spawned process. */
17
18 int spawn (char* program, char** arg_list)
19 {
20 pid_t child_pid;
21
22 /* Duplicate this process. */
23 child_pid = fork ();
24 if (child_pid != 0)
25 /* This is the parent process. */
26 return child_pid;
27 else {
28 /* Now execute PROGRAM, searching for it in the path. */
29 execvp (program, arg_list);
30 /* The execvp function returns only if an error occurs. */
31 fprintf (stderr, "an error occurred in execvp\n");
32 abort ();
33 }
34 }
35
36 int main ()
37 {
38 /* The argument list to pass to the "ls" command. */
39 char* arg_list[] = {
40 "ls", /* argv[0], the name of the program. */
41 "-l",
42 "/",
43 NULL /* The argument list must end with a NULL. */
44 };
45
46 /* Spawn a child process running the "ls" command. Ignore the
47 returned child process id. */
48 spawn ("ls", arg_list);
49
50 printf ("done with main program\n");
51
52 return 0;
53 }