满意答案
atmcleaner
2013.08.26
采纳率:48% 等级:12
已帮助:9682人
#include
#include
#define MAXARGS 20 /* cmdline args */
#define ARGLEN 100 /* token length */
main()
{
char *arglist[MAXARGS+1]; /* an array of ptrs */
int numargs; /* index into array */
char argbuf[ARGLEN]; /* read stuff here */
char *makestring(); /* malloc etc */
numargs = 0;
while ( numargs < MAXARGS )
{
printf("Arg[%d]? ", numargs);
if ( fgets(argbuf, ARGLEN, stdin) && *argbuf != '/n' )
arglist[numargs++] = makestring(argbuf);
else
{
if ( numargs > 0 )
{
arglist[numargs]=NULL; /* close list*/
execute( arglist ); /* do it */
numargs = 0; /* and reset*/
}
}
}
return 0;
}
execute( char *arglist[] )
{
int pid,exitstatus; /* of child */
pid = fork(); /* make new process */
switch( pid ){
case -1:
perror("fork failed");
exit(1);
case 0:
execvp(arglist[0], arglist); /* do it */
perror("execvp failed");
exit(1);
default:
while( wait(&exitstatus) != pid );
printf("child exited with status %d,%d/n",
exitstatus>>8, exitstatus&0377);
}
}
char *makestring( char *buf )
/*
* trim off newline and create storage for the string
*/
{
char *cp, *malloc();
buf[strlen(buf)-1] = '/0'; /* trim newline*/
cp = malloc( strlen(buf)+1 ); /* get memory*/
if ( cp == NULL ){ /* or die */
fprintf(stderr,"no memory/n");
exit(1);
}
strcpy(cp, buf); /* copy chars */
return cp; /* return ptr */
}
01分享举报