// try running commands '/bin/ls / > abcde' // '/bin/cat < abcde' #include #include #include #include #include #include #include using namespace std; void runcommand(char *cmd, char*argv[], char* readfile, char* writefile) { int status, i; cout << "cmd = " << cmd << "\n"; i=0; while (argv[i]!= NULL) { cout << "argv[" << i << "] = " << argv[i] << "\n"; i++; } cout << "readfile = " << readfile << "\n"; cout << "writefile = " << writefile << "\n"; if (fork() == 0) { if ((readfile != NULL) && (readfile[0] != '\0')) { int fd = open(readfile, O_RDONLY); if (fd == -1) {cerr << "error\n", exit(0);} close(0); dup(fd); close(fd); } if ((writefile != NULL) && (writefile[0] != '\0')) { int fd = open(writefile, O_CREAT | O_WRONLY, 00777); if (fd == -1) {cerr << "error\n", exit(0);} close(1); dup(fd); close(fd); } int stat = execv(cmd, argv); if (stat == (-1)) {cerr << "error\n", exit(10);} } int stat = wait(&status); if (stat == -1) {cerr << "error return from wait\n";} } // example6.cpp int main() { char buf[1000]; char cmd[100]; int i, j, k; char arg[10][100]; char *argv[10]; char readfile[100]; char writefile[100]; while (fgets(buf, 1000, stdin)) { for (i=0; i<10; i++) arg[i][0] = '\0'; readfile[0] = '\0'; writefile[0] = '\0'; // my assumption about the command is // (1) first word is always the command // (2) ">" and "<" are separated by a space from other words // (3) "<" and ">" are used correctly // (4) There are at most ten words in a line i = sscanf(buf, "%s %s %s %s %s %s %s %s %s %s", arg[0], arg[1], arg[2],arg[3],arg[4],arg[5],arg[6], arg[7],arg[8],arg[9]); for (k=0; k") == 0) { strcpy(writefile, arg[j+1]); for (k = j+2; k