I actually posted this problem on a different forum, but figured this would be a more appropriate place to post it.
OK so I've created my own shell, but I can't get the background process function to run properly! What I want to do is to run a process in the background, and also print when the job is finished. The printing part is where I've been having some problems.
So if I type sleep 5 &, it works and prints out when finished. However, if I type sleep 5 &, and then type in another command like ls or ps after it, the shell hangs and it prints out that it's finished when it clearly has not finished.
void handler(int sig)
{
int pid;
int status;
pid = wait(NULL);
printf("Pid %d exited.\n", pid);
}
int runInBackground(Command* command, int givenPath)
{
int pid;
int status;
char *commandName = command->name;
if(givenPath == 0)
{
commandName = getCommandPath(command->name);
}
if(commandName == NULL)
{
printf("Command not found.\n");
return 1;
}
pid = fork();
if(pid < 0) //Checks for error
{
}
if(commandName == NULL)
{
printf("Command not found.\n");
return 1;
}
pid = fork();
if(pid < 0) //Checks for error
{
printf("Error in the fork process.\n");
return 1;
}
else if (pid == 0) //Child
{
execv(commandName, command->argv);
return 1;
}
else
{
signal(SIGCHLD, handler);
}
}
OUTPUT:
<project3> sleep 5 &
<project3>
<project3>
<project3> Pid 399 exited.
<project3>
<project3> sleep 5 &
<project3> ls
bob project1.c hey proj1 proj1.c
Pid 402 exited.
I pressed enter a few times the first time I ran sleep 5 in the background, then after 5 seconds, it printed out the pid perfectly! But notice what happens when I ran sleep 5 in the background and then ran ls following it right afterwards. System printed out my files/folders but posted the pid and got hung.