1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | //============================================================================ // Name : unix.cpp // Author : xiaoguozi // Version : // Copyright : Your copyright notice // Description : read command from stdin to exec,Ansi-style //============================================================================ #include "apue.h" #include <dirent.h> #include <iostream> #include <sstream> #include <vector> #include <sys/wait.h> using namespace std; #define BUFSIZE 4096 static void sig_int( int ){ printf ( "interrupt\n" ); } int main( int argc, char *argv[]) { string cmd; pid_t pid; int status; if (:: signal (SIGINT,sig_int) == SIG_ERR) err_sys( "signal error" ); while (getline(cin,cmd)){ stringstream ios; ios<<cmd; string tmp; vector<string> vec; while (ios>>tmp){ vec.push_back(tmp); } if (vec.size()>4){ err_sys( "arguments must less than 4" ); //continue; } if ((pid=fork())<0){ err_sys( "fork error" ); } else if (pid==0){ if (vec.size()==1) execlp(vec[0].c_str(),vec[0].c_str(),( char *)0); else if (vec.size()==2) ::execlp(vec[0].c_str(),vec[0].c_str(),vec[1].c_str(),( char *)0); else if (vec.size()==3) ::execlp(vec[0].c_str(),vec[0].c_str(),vec[1].c_str(),vec[2].c_str(),( char *)0); else if (vec.size()==4) ::execlp(vec[0].c_str(),vec[0].c_str(),vec[1].c_str(),vec[2].c_str(),vec[3].c_str(),( char *)0); exit (127); } if ((pid=::waitpid(pid,&status,0))<0){ err_sys( "wait error" ); } cout<< "% " <<pid<<endl; } return 0; } |