I am trying to implement a simple shell. Everything else works fine except for the error handling.
When I try to do execute an invalid command like "cat ff", in which "ff" does not exist, I got this:
The expected behavior should be like the third one "catt f". It must start with "ERROR:" and then the error message, which means it should be "ERROR:cat: ff: No such file or directory"
How should I modify my code to achieve that? Thanks in advance!
#include <fcntl.h>
#include <iostream>
#include <unistd.h>
#include <cstring>
#include <errno.h>
#include <sys/wait.h>
using namespace std;
int main(){
int pid;
int status;
char *cmd[] = {"cat", "ff", NULL};
if ((pid = fork()) == 0){
if (execvp(cmd[0], cmd) == -1){
cout << "ERROR:" << strerror(errno) << '\n';
}
}else if (pid == -1){
cout << "ERROR:" << strerror(errno) << '\n';
}else{
waitpid(pid, &status, 0);
cout << "Status: " << status << '\n';
}
}
The status here isn't very much necessary here. It is just my attempt to figure out whether it comes before that error message. I am super new to this and I am very confused and lost. Please forgive me if I did anything unnecessarily.