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