/** * This program forks a separate process using the fork()/exec() system calls. * * Figure 3.10 * * @author Gagne, Galvin, Silberschatz * Operating System Concepts - Seventh Edition * Copyright John Wiley & Sons - 2005. */ #define _GNU_SOURCE #include #include #include #include #include #include #include int main (int argc, char **argv) { char *my_command = NULL; size_t n, t; int m; pid_t pid; char *comm_copy; my_command = (char *) malloc (80 * sizeof (char)); fprintf (stdout, " Enter a command:> "); fgets (my_command, 79, stdin); n = strlen (my_command) - 1; /* Remove the EOL character */ my_command[n] = '\0'; /* Set last char to NULL character */ /* fprintf(stdout," %s %d\n", my_command, n);*/ /* fork a child process */ pid = fork (); if (pid < 0) { /* error occurred */ fprintf (stderr, "Fork Failed\n"); exit (-1); /* Get out. */ } else if (pid == 0) { /* child process */ printf ("** I am the child %d **\n", pid); comm_copy = (char *) malloc (80 * sizeof (char)); strcpy (comm_copy, strrchr (my_command, '/') + 1); /* Copy the last part of the filename, past final '/' char. */ fprintf (stdout, " IN CHILD: Pointer value: %s %s\n", my_command, comm_copy); if (execlp (my_command, comm_copy, NULL) < 0) { perror ("Child"); /* Print a meaningful error statement */ exit (-1); /* This should not be reached if execlp succeeds. */ } } else { /* parent process */ /* parent will wait for the child to complete */ printf ("I am the parent %d\n", pid); /* fprintf(stdout," IN PARENT: Pointer value: %x\n %s\n", my_command, my_command); */ /* wait (NULL); printf ("Child Complete\n"); */ exit (0); } }