Using waitpid to run a process in the background?

I am trying to imitate the bash function of starting a process in the background if "&" is at the end of the command. I have the following function ... and I don’t think that it does what I want it to do

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; } 

If I just ran "ls -l", it works as expected. but if I want to run ls in the background ... and the program continues to accept new commands, I call the function with the background flag set to 1, and I want it to execute this process in the background, say that it created this process ... and then offer to accept the next command.

+7
source share
2 answers

I do not think waitpid(-1, &cstatus, WNOHANG); does what you think does. You need to check its return value. If it is > 0 , then the PID of the child process that exited. If it is 0 or -1 , the child process has not changed.

You can simply call waitpid(-1, &cstatus, WNOHANG); before and / or after each command you run. Call it in a loop to catch more than one child exit.

You can also handle SIGCHILD. Your process will receive this signal immediately after exiting the game, which is good if you want to immediately report the completion of a child process without waiting for user input.

+4
source

It's simple. You have a process P with id pid.

If you want it to run in the background (which can be recognized at the end of the input line for the shell / program), you must do this

 //some code id=fork(); if(id==0) { //child does work here } else { //Parent does work here if(!strcmp(last string,"&")==0)waitpid(id,&status,0); } 

This way the parent does not wait if you request background execution, otherwise it waits.

+2
source

All Articles