|
|
1.1 root 1: #include <stdio.h>
2:
3: FILE *newfp;
4: int oldstdout;
5:
6: main()
7: {
8: extern int system();
9:
10: ropen("list.fil");
11: system("ls *.c");
12: rclose();
13: }
14:
15: /*
16: * Redirect stdout prior to system() call.
17: * You can't redirect child process's I/O
18: * but you can redirect main()'s and let the child inherit it.
19: */
20: ropen(tofile)
21: char *tofile;
22: {
23: if ((newfp = fopen(tofile, "wr")) == NULL)
24: fatal("cannot open output file \"%s\"", tofile);
25:
26: /* Duplicate stdout so it can be restored later */
27: if ((oldstdout = dup(fileno(stdout))) == -1)
28: fatal("dup failed");
29:
30: /* Force duplication of new file handle as stdout */
31: if (dup2(fileno(newfp), fileno(stdout)) == -1)
32: fatal("dup2 failed");
33: }
34:
35: /*
36: * Terminate redirection
37: */
38: rclose()
39: {
40: /* Restore old stdout */
41: if (dup2(oldstdout, fileno(stdout)) == -1)
42: fatal("dup2 failed");
43: /* Close the extra handle */
44: if (close(oldstdout) != 0)
45: fatal("cannot close old stdout");
46: fclose(newfp);
47: }
48:
49: /*
50: * Fatal error
51: */
52: fatal(p)
53: char *p;
54: {
55: fprintf(stderr, "system: %r\n", &p);
56: exit(1);
57: }
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.