I'm trying to write a shell in c and I want to implement the behavior of "cat > file" to then let me write into a file.
My main function:
int main (int argc, char **argv)
{
pid_t childPid;
int status;
char * cmdLine;
int EXIT = 1;
parseInfo info;
int fd[2];
char buffer[1024];
char* env = getenv("USER");
char cwd[BUFFER];
if (getcwd(cwd, sizeof(cwd)) == NULL) {
perror("getcwd() error");
return 1;
}
while (EXIT){
printf("%s@%s > ",env,cwd);
cmdLine = readline();
info = parse(cmdLine);
info.cwd = cwd;
pipe(fd);
childPid = fork();
if (childPid == 0)
{
executeCommand(info,fd);
}
else
{
close(fd[1]);
if((read(fd[0], buffer, 1024 * sizeof(char))) == -1){
printf("Failed reading from pipe.\n");
}
else{
if(!strcmp(info.cmd,"cd")){
strcpy(cwd,buffer);
chdir(buffer);
}
}
while (wait(&status) != childPid);
}
}
}
the executeCommand:
void executeCommand(parseInfo info,int* fd){
//print_info(info); // FOR DEBUGGING
if(!strcmp(info.cmd,"cat")){
cat(info);
}
else if(!strcmp(info.cmd,"cd")){
info.cwd = changedir(info,info.cwd);
if(write(fd[1], info.cwd, ((strlen(info.cwd)+1)* sizeof(char))) == -1)
printf("Error while writing into pipe\n");
}
else if(execvp(info.cmd,info.args) == -1){
printf("Error: unknown command [%s]\n",info.cmd);
}
exit(1);
}
Here's my cat function:
void cat(parseInfo info){
char* write_to_file = ">";
char* append_to_file = ">>";
if(!strcmp(info.args[1],write_to_file) || !strcmp(info.args[1],append_to_file)){
if (info.args[2] == NULL){
printf("unsupported sytax, file name expected.\n");
}
char* line;
FILE* fp;
if(!strcmp(info.args[1],write_to_file))
fp = fopen(info.args[2],"w");
if(!strcmp(info.args[1],append_to_file))
fp = fopen(info.args[2],"a");
while(1){
line = readline();
fputs(line,fp);
}
fclose(fp);
}
}
How do I make ctrl-c not kill the parent process and just run fclose and kill the child only? Or is there another method that's better here? I'm not sure how to implement this.