If the command parameter does not contain "/" the executable is searched in PATH.
If waitExecution is true the function waits for the process to be finished.
Throws errno in case of failed forking,failed redirection when waitExecution is true and failed background handling and initiation of the new process.
redIn,redOut should be NULL if no redirection is required,append should be true if output needs to be redirected to a file,appened at the end.
Check LinuxShell for missing methods and complete source code.
void execute(const char *command, char *const args[],bool waitExecution,const char *redIn,const char* redOut,bool append){ pid_t pidChild; pidChild = fork(); if (pidChild== 0) {//executed in child int in=-1,out=-1; if(redIn!=NULL){ try{ in=startRedirectIn(redIn); }catch(int ex){ if(waitExecution){ throw ex; }else{ exit(ex); } } } if(redOut!=NULL){ try{ out=startRedirectOut(redOut,append); }catch(int ex){ if(waitExecution){ throw ex; }else{ exit(ex); } } } stopRedirect(in); stopRedirect(out); execvp(command,args); exit(1); }else if (pidChild < 0) {//fork failed throw errno; } else{// executed in parent if(waitExecution){ int childExitStatus; if(wait(&childExitStatus)!=-1){ if(WIFEXITED(childExitStatus)){ int exitStatus=WEXITSTATUS(childExitStatus); if(exitStatus!=0){ throw exitStatus; } }else{ throw errno; } } }else{ if(kill(pidChild,0)==0){ if(kill(pidChild,SIGSTOP)==0){ backgroundProcs.push_back(pidChild); }else{ throw errno; } }else{ throw errno; } } } }
No comments:
Post a Comment