I am making a shell and trying to understand the function of fork it (Only the code with issue is shown below).
However, After adding fork();
my shell is not exiting with the command exit. I know I can use kill(pid, SIGKILL)
to achieve this but I do not want to show any exit status. I think exit(0);
should work without the need of kill(pid, SIGKILL)
.
A simple explanation with the code would help a lot.
Update: I want to accept continuous commands until exit.
#include <iostream>
#include <sys/wait.h>
#include <vector>
#include <string>
#include <chrono>
#include <algorithm>
#include <unistd.h>
using namespace std;
typedef struct cmds{
string cmd;
} cmds;
bool operator<(cmds &as1, cmds &bs1){
return as1.durr<bs1.durr;
}
int main() {
vector <cmds> lst;
cmds ant;
string cmd;
pid_t pid = fork() ;
while (1){
if(pid==0){
cout<<"$>";
getline(cin,cmd);
ant.cmd=cmd;
string comd;
for(int i=0;i<cmd.length();i++){
if(cmd[i]!=' ')
comd+=cmd[i];
}
if(comd=="exit"){
exit(0);
}
else{
char s[256]="";
for (int i=0; i<cmd.length(); i++)
s[i]=cmd[i];
}
lst.push_back(ant);
}
else
wait(NULL);
}
}
**Expected output** - //The shell should end without any cout or exit status//
**Actual output** - //The shell does not end and you can type anything and enter and continue - however no '$' is present and you cannot use any shell commands//
Apologies for any messy writing - The new UI for writing questions is hard to use.
Your parent process is stuck in while(1)
loop. Add break;
line after wait(NULL);
.