23,125
社区成员
发帖
与我相关
我的任务
分享
/*
* psh2.c
* solves the 'one-shot ' porblen of version 0.1
* uses execvp () , but fork () s first so that the
* shell waits around to perform another command
* new Problem : shell catches signals , runvi ,Press ^s
*/
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#define MAXARGS 20
#define ARGLEN 100
int main ()
{
char *arglist[MAXARGS + 1] ;
char argbuf[ARGLEN ] ;
int numargs =0 ;
char *makestring (char *buf) ;
void execute (char *list[] ) ;
while ( numargs < MAXARGS )
{
printf (" arg[%d]? \n",numargs ) ;
if ( fgets ( argbuf , ARGLEN , stdin ) && *argbuf != '\n' )
{
if ( strncmp ( argbuf , "quit" , 4 ) == 0 )
exit ( 1 ) ;
else
arglist[numargs++] = makestring ( argbuf );
}
else
{
if ( numargs > 0 )
arglist[numargs] =NULL ;
execute ( arglist ) ;
numargs =0 ;
}
}
return 0 ;
}
void execute ( char *list[] )
{
int pid , exitstatus ;
pid = fork () ;
switch ( pid ) {
case -1 : perror ( " fork feld " ) ; exit (1 ) ;
case 0 :
execvp ( list[0] , list ) ;
perror ( "execute error " ) ;
exit ( 2 ) ;
default :
while ( wait ( & exitstatus ) !=pid ) ;
printf ( " child exit whith status %d %d \n" , exitstatus>>8 , exitstatus &0x377 ) ;
}
}
char *makestring ( char *buf )
{
char *cp ;
int len ;
len = strlen( buf ) ;
buf [len-1 ] = '\0' ; /*here is very improtant , if buf[len ] , it will include the '\n' */
cp = ( char * ) malloc ( len +1 ) ;
if ( cp == NULL )
{
perror ( " malloc erro " ) ;
exit ( 2 ) ;
}
strcpy ( cp , buf ) ;
return cp ;
}