コマンドの最後に「&」が見つかった場合、バックグラウンドでプロセスを実行するbash機能を模倣しようとしています。私は次の機能を持っています...そして、私がやりたいことをしているとは思いません
int execute(char* args[],int background,int *cstatus){
pid_t child;
pid_t ch; /*Pid of child returned by wait*/
if ((child = fork()) == 0){ /*Child Process*/
execvp(args[0],args);
fprintf(stderr, "RSI: %s: command not found\n",args[0]); /*If execvp failes*/
exit(1);
}else{ /*Parent process*/
if (child== (pid_t)(-1)) {
fprintf(stderr,"Fork failed\n"); exit(1);
}else{
if (background==0){ /*If not running in background..wait for process to finish*/
ch = wait(cstatus);
}else{
printf("%ld Started\n",(long)getpid());
/* printf("Parent: Child %ld exited with status = %ld\n", (long) ch, (long)cstatus);
*/ }}
}
return 0;
}
int wait_and_poll(int *cstatus){
pid_t status;
status = waitpid(-1,cstatus,WNOHANG);
if (status>0){
fprintf(stdout,"%ld Terminated.\n",(long) status);
}
return 0;
}
「ls -l」を実行するだけで期待どおりに動作します..しかし、バックグラウンドで ls を実行し、プログラムに新しいコマンドを受け入れさせ続ける場合は、バックグラウンド フラグを 1 に設定して関数を呼び出します。プロセスをバックグラウンドで実行し、プロセスが作成されたことを伝えてから、次のコマンドを受け入れるように求めます。