Debian Codegraph @

listings/chapter-11/diskfree.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 <stdlib.h>
8 #include <string.h>
9 #include <sys/types.h>
10 #include <sys/wait.h>
11 #include <unistd.h>
12
13 #include "server.h"
14
15 /* HTML source for the start of the page we generate. */
16
17 static char* page_start =
18 "<html>\n"
19 " <body>\n"
20 " <pre>\n";
21
22 /* HTML source for the end of the page we generate. */
23
24 static char* page_end =
25 " </pre>\n"
26 " </body>\n"
27 "</html>\n";
28
29 void module_generate (int fd)
30 {
31 pid_t child_pid;
32 int rval;
33
34 /* Write the start of the page. */
35 write (fd, page_start, strlen (page_start));
36 /* Fork a child process. */
37 child_pid = fork ();
38 if (child_pid == 0) {
39 /* This is the child process. */
40 /* Set up an argumnet list for the invocation of df. */
41 char* argv[] = { "/bin/df", "-h", NULL };
42
43 /* Duplicate stdout and stderr to send data to the client socket. */
44 rval = dup2 (fd, STDOUT_FILENO);
45 if (rval == -1)
46 system_error ("dup2");
47 rval = dup2 (fd, STDERR_FILENO);
48 if (rval == -1)
49 system_error ("dup2");
50 /* Run df to show the free space on mounted file systems. */
51 execv (argv[0], argv);
52 /* A call to execv does not return unless an error occurred. */
53 system_error ("execv");
54 }
55 else if (child_pid > 0) {
56 /* This is the parent process. Wait for the child process to
57 finish. */
58 rval = waitpid (child_pid, NULL, 0);
59 if (rval == -1)
60 system_error ("waitpid");
61 }
62 else
63 /* The call to fork failed. */
64 system_error ("fork");
65 /* Write the end of the page. */
66 write (fd, page_end, strlen (page_end));
67 }