1

I'm making a simple shell, and I need to be able to run a command such as sleep 5 &. The & tells it to run as a background process, so I can input other commands such as cd someDirectory while the child process "sleeps" in the background.

I have it set up so that it forks correctly, but how do I set it up so that it can run a child in the background when given an &?

I've looked a lot into WNHONANG and doing things such as waitpid(pid, &status, WNHONANG), but it makes it so nothing at all works.

Here's my code:

int executeCommand(char **args){
    pid_t pid;
    int status;
    
    pid = fork();
    //error in fork
    if(pid < 0){
        printf("Fork Failed\n");
        exit(1);
    }
    //child process
    if(pid == 0){
        //child executes process
        execvp(args[0], args);
        
        //if execution fails
        exit(1);
    }
    //parent process
    else{
        waitpid(pid, &status, 0);
    }
    //Do I need this?
    kill(pid, SIGKILL);
    return 1;
}

ESM
  • 175
  • 10
  • 5
    Don't call `waitpid`. Foreground and background are shell concepts and not inherent to how `fork` works. If you don't "wait" for the child to exit before allowing the next command then by definition that means it is running in the background. – kaylum Sep 21 '20 at 00:28
  • 3
    Don't kill the process either ;) – Matheus Rossi Saciotto Sep 21 '20 at 00:33
  • So would I just get rid of the last `else` statement? And then just simply check to see if the child process is finished? – ESM Sep 21 '20 at 00:34
  • You probably want to make the `else` conditional on whether the commands need to be background or foreground. And then yes for background processes have different code to reap any child processes that exit - that's a different topic and suggest you research how to do that and ask a new question if needed. – kaylum Sep 21 '20 at 00:37
  • Note that you will need to wait for child processes with WNOHANG every so often to prevent your shell from collecting zombies. You'll need to think carefully about how to handle reaped (waited for) children other than background processes too. – Jonathan Leffler Sep 21 '20 at 05:44
  • 1
    Does this answer your question? [Regarding background processes using fork() and child processes in my dummy shell](https://stackoverflow.com/questions/8319484/regarding-background-processes-using-fork-and-child-processes-in-my-dummy-shel) – ggorlen Oct 23 '22 at 02:54

0 Answers0