实验代码
#include <stdio.h> #include <string.h> void exec(char cmd[]) { int f = 0, i, l; l = strlen(cmd); for (i = 0; i < l; i++) { if (cmd[i] == '|') { f = 1; break; } } if (!f) { system(cmd); } else { FILE *fr, *fw; char commands[2][256]; char result[256]; cmd[l] = '|'; int k, n; k = 0; n = 0; for (i = 0; i <= l; i++) { if (cmd[i] != '|') { commands[n][k] = cmd[i]; k++; } else { commands[n][k] = '\0'; k = 0; n++; } } fr = popen(commands[0], "r"); fw = popen(commands[1], "w"); fread(result, 256 * sizeof(char), 1, fr); fwrite(result, sizeof(char), strlen(result), fw); pclose(fr); pclose(fw); } } int main() { char cmd[256], c; int i; while (1) { printf("OSLab2 -> "); i = 0; while ((c = getchar()) != '\n') { if (c != ';') { cmd[i] = c; i++; } else { cmd[i] = '\0'; exec(cmd); i = 0; } } cmd[i] = '\0'; if (strcmp(cmd, "exit")) { exec(cmd); } else { break; } } return 0; }