# Include <sys/types. h> <br/> # include <sys/Wait. h> <br/> # include <stdio. h> <br/> # include <signal. h> <br/> # include <unistd. h> <br/> # define maxargs 20 <br/> # define arglen 100 <br/> main () <br/>{< br/> char * Arglist [maxargs + 1]; <br/> int numargs; <br/> char argbuf [arglen]; <br/> char * makestring (); </P> <p> numargs = 0; <br/> while (numargs <maxargs) <br/> {<br/> printf ("Arg [% d]? ", Numargs); <br/> If (fgets (argbuf, arglen, stdin) & * argbuf! = '/N') <br/>{< br/> Arglist [numargs ++] = makestring (argbuf ); <br/>}< br/> else <br/>{< br/> If (numargs> 0) <br/>{< br/> Arglist [numargs] = NULL; <br/> execute (Arglist); // zhixing <br/> numargs = 0; <br/>}</P> <p> execute (char * Arglist []) <br/>{< br/> int PID, exitstatus; </P> <p> pid = fork (); </P> <p> switch (PID) <br/>{< br/> case-1: <br/> perror ("fork failed! "); <Br/> exit (1); <br/> case 0: <br/> execvp (Arglist [0], Arglist ); <br/> perror ("execvp failed! "); <Br/> exit (1); <br/> default: <br/> while (wait (& exitstatus )! = PID) <br/>; <br/> printf ("Child exit with status % d, % d/N", exitstatus> 8, exitstatus & 0377 ); </P> <p >}</P> <p> char * makestring (char * BUF) <br/>{< br/> char * CP, * malloc (); </P> <p> Buf [strlen (BUF)-1] = '/0 '; <br/> CP = malloc (strlen (BUF) + 1); </P> <p> If (Cp = NULL) <br/>{< br/> fprintf (stderr, "no memory/N"); <br/> exit (1 ); <br/>}< br/> strcpy (CP, Buf); <br/> return CP; <br/>}< br/>
This is an example from the Unix/Linux Programming Practice tutorial.
In addition to Linux system calls, it is worth noting that there are still some details.
For example, processing strings accepted by the fgets () function.
Char * fgets (char * s, int size, file * stream );
Fgets () reads in at most one less than size characters from stream and
Stores them into the buffer pointed to by S. Reading stops after
EOF or a newline. If a newline is read, it is stored into the buffer.
A'/0' is stored after the last character in the buffer.
The fgets function reads 1 character less from the data stream than the size and stores them in the buffer zone pointed to by S. If you encounter EOF or line feed
Stop. If it is a line break, the line break is also stored in the buffer zone. '/0' is stored at the end of the buffer.
Therefore, remove the '/N' generated by the key in the process and use the makestring (char * BUF) function.