/* * Assignment Four * * Write a program that: * A. Creates a child which waits for a command. * B. The child looks for the stdout redirection * operator and if present redirects stdout, * otherwise it just executes the program. * C. If the output file name does not exist, create the file. * D. The child terminates upon command completion * (so the FDs will reset for the next cmd). * E. When a the EOF condition (^D) is detected, * the parent and child programs terminate. * * Use the script program to show the program source code, * its compilation, and run time behavior. Show BOTH * success and failure when executing the command. * * Here is a starting program that forks a child, * assumes the ls command is typed with the redirection * operator to a file called "lsout". * * Begin by testing this example with and without the * lsout file. (Use "touch lsout" to create the file.) * You must add to this program: * A. The ability to run the program if the ">" feature * was not used. (The user did not want I/O redirection.) * B. The ability to create a new file for output. * C. The ability to loop over multiple commands. * D. The ability to terminate on the ^D or EOF command. * */ #include /* Defines printf() and other fxxxxx() I/O services */ #include /* Defines exit() and other library support routines */ #include /* Defines exec() family of services */ #include #include char command[255] = "/bin/ls -l > lsout"; main (int argc, char *argv[], char *envp[]) { register char *cmdptr, **p; int pid, status; int fd1, fd3; for (p = argv; *p ; p++) { printf ("%s\n", *p); } if (!fork()) { /* Child code */ printf ("Yo Dude...\n"); // gets (command); printf ("%s\n", command); /* Char routines defined in /usr/include/string.h */ cmdptr = strchr (command, '>'); while (*(++cmdptr) == ' ') ; printf ("%s\n", cmdptr); /* Make sure your string is null terminated */ /* O_XXXX bits defined in "man 2 open" */ if ((fd3 = open (cmdptr, O_RDWR)) < 0) { printf ("Cannot open %s\n", cmdptr); goto error; } else printf ("Opened file \"%s\" with file descriptor %d\n",\ cmdptr, fd3); close (1); if ((fd1 = dup (fd3)) < 0) { /* Stream I/O defined in /usr/include/stdio.h */ fprintf (stderr, "Duplicate failed\n"); goto error; } else fprintf (stderr, "The new fd is %d\n", fd1); if (close (fd3) >= 0) { fprintf (stderr, "%s closed\n", cmdptr); } else { fprintf (stderr, "%s did not close\n", cmdptr); error: printf ("%s: Cannot set up \"%s\" command\n", argv[0], command); exit (123); } /* Assume "/bin/ls -l" is to be executed */ command[7] = 0; command[10] = 0; if (execl (command, command, &command[8], 0)) /* -1 return means error */ fprintf (stderr, "%s: Cannot find or access %s\n", argv[0], command); exit (0); } else { /* Parent code */ pid = wait (&status); printf ("Statushigh = %d, Statuslow = %d, PID = %d\n", ((status & 0xff00) >> 8), (status & 0xff), pid); } }