I am trying to implement my own shell and am experimenting with background jobs with using WNOHANG option in waitpid. But whenever I run a command in shell it just prints the output next to my prompt like this:
user@hostmachine:/.../$: [output]
Where am I going wrong? `
while (1) {
int childPid, status;
// Display prompt and read input
char *buffer = print_prompt();
char *input = readline(buffer);
check_and_free(buffer)
// add input to readline history.
add_history(input);
time_t t;
time(&t);
add_history_time(ctime(&t));
// Check for EOF.
if (!input)
break;
parseInfo *result = parse(input);
if (result == NULL) {
goto free;
}
print_info(result);
commandType *input_command = &result->CommArray[0];
// execute builtin command in parent process
int commType = isBuiltInCommand(input_command->command);
if (commType == EXIT) {
free_info(result);
check_and_free(input)
exit(0);
}
else if (commType != NO_SUCH_BUILTIN) {
executeBuiltInCommand(input_command, commType, history_get_history_state());
} else {
// create a child process to execute command
childPid = fork();
if (childPid == 0) {
// calls execvp
printf("Executing child process...\n\n");
executeCommand(input_command, result);
} else {
waitpid(childPid, &status, WNOHANG);
if (status != 0) {
printf("Error! Child exited with error code %d\n", WEXITSTATUS(status));
}
}
}
// Free buffer that was allocated by readline
free:
free_info(result);
check_and_free(input)
}
return 0;
}
`
I tried to execute a job in background and for quick ones like "ls" it just prints the output next to my prompt!