It took me a bit to write this evening. It started with argv, which is a two-digit array.ProgramIt is always not displayed. later it was found that execvp only supports pointer array =. = Okay ....
Program idea: After the sub-process is enabled, close the standard output of the sub-process, and then create a new file in the sub-process, at this time, the file will select the smallest File Identifier in its process as the File Identifier of the file, that is, FD
Therefore, in the future, all the standard output of the sub-process will flow to the file. This should be a simple idea. I feel that the GNU source code should use an unknown pipeline, it is even implemented by famous pipelines (Network Transmission). Well, I don't want to get involved... If you are interested, go to the official website to find the GNU/Linux Shell.Source code
/* 1.C * Author: wangshiyang * Date: 2013/5/13 */# include <stdio. h> # include <unistd. h> # include <string. h> // ----------------------------------------------------/* For the convience I 'v set a lot of global-variables | * the formal shell program may not dit like this | ** // warning: use argv [] [] is wrong !!! | Char input [100]; // The command you input | char * argv [30]; // The execvp must use point array | char file [100]; // You can input a filename | // -------------------------------------------------------- char * newstr (char * s, int L) {char * Rv = (char *) malloc (L + 1 ); RV [l] = '\ 0'; strncpy (RV, S, L); Return RV;} int deal () // deal the input command {char temp [100]; int Len, I, A, turn; fgets (input, 100, stdin); Len = Strlen (input); turn = 0; a = 0; for (I = 0; I <Len; I ++) {If (input [I] = '\ n') {argv [turn ++] = newstr (temp, strlen (temp); break ;} if (input [I]! = '') {Temp [A ++] = input [I]; temp [a] = '\ 0 ';} else {argv [turn ++] = newstr (temp, strlen (temp); a = 0 ;}}for (I = 0; I <turn; I ++) if (! Strcmp (argv [I], ">") {strcpy (file, argv [I + 1]); // copy the filename to file arrayreturn I ;} return-1 ;}; void execute (INT flag) // run the command {intpid, FD; argv [flag] = NULL; If (pid = fork ()) =-1) {perror ("fork"); exit (1);} If (pid = 0) {/* 0 for stdin, 1 for stdout, 2 For stderr */close (1); // close the stdout FD = creat (file, 0777); // then open and FD connect to 1 execvp (argv [0], argv ); // And runperror ("execvp"); exit (1);} If (PID! = 0) {Wait (null); printf ("father done \ n") ;}}; void free_all () // free all the pointers {int I; for (I = 0; I <30; I ++) Free (argv [I]); printf ("all the pointer have been free .. ")}; int main () {int flag; printf (" Please input a command, please using the '>' \ n "); printf (" Example: ls-Ail> 123 \ n "); flag = deal (); If (flag =-1) {fprintf (stderr," input wrong! Do not include '>' \ n "); exit (1);} execute (FLAG); free_all (); Return 0 ;}