diff --git a/Examples/DupExecDemo.c b/Examples/DupExecDemo.c new file mode 100644 index 0000000000000000000000000000000000000000..9e3c95c31686269e6d8e8dd89aa47d17d19ca026 --- /dev/null +++ b/Examples/DupExecDemo.c @@ -0,0 +1,53 @@ +// This code is intended to demo small pieces of code relevant to a shell +// dup2, execv() in particular +// In addition, the most useful makeargv() method will be used + +//#include "makeargv.h" +#include <stdio.h> +#include "apue.h" +#include <stdlib.h> +#include <unistd.h> +#include <fcntl.h> // OverKill +#include <errno.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <string.h> + +int makeargv(char *, char *, char ***); + + +int main() { + int NewFD; + int i; + int j; + char ** ExecVectors; + + write(STDOUT_FILENO, "To Console\n", 11); + + // Now open a file and get a file descriptor + mode_t mode = S_IRUSR | S_IWUSR | S_IXUSR; // FOR OPEN AND CREATE OF FILES + int oflag = O_CREAT | O_RDWR | O_TRUNC; + + NewFD = open("DummyFile", oflag, mode); //just making a file + printf("DummyFile descriptor is %u\n", NewFD); //printing to STDOUT + + NewFD = dup2(NewFD, STDOUT_FILENO); //now STDOUT is pointing to the file + printf("Dup File descriptor is %u\n", NewFD); //printing to STDOUT + //that is redirected to file + + write(STDOUT_FILENO, "To Console ?\n", 13); //no, to the file + + ///////////////////////////////////////////////////////////////////////////// + //Now lets mess with executing things + + j = makeargv(" \nls -l / | cat DupExecDemo.c ? ls -l . ", "\t \n", &ExecVectors); + //^^^^^^^^( command delimeters start of command + //returns number of tokens, which is 6 + + for (i = 0; i < j; i++) + fprintf(stderr, "%s\n", ExecVectors[i]); //stderr finds its way to + //console anyway + + ExecVectors[3] = NULL;ExecVectors[6]=NULL; + execvp(ExecVectors[7], &ExecVectors[7]); +}