This program does two things: 1) Duplicates the action of shell 2) Record user input to a tmp.log file
The problem here is that in my child process, printf("ABC"); does nothing. Outputting the log file works fine, but it just doesn't print.
Why does this behave like this?
I know execvp is supposed to replace the current process but that doesn't explain why it would execute the output but not the print. I saw the below link but this doesn't answer my question. exevp skips over all code until wait call in c
#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <wordexp.h>
void execute(char *user_input)
{
pid_t pid;
int state_loc;
if( (pid = fork()) == -1){
printf("fork failed\n");
exit(1);
}
else if(pid == 0){
FILE *f;
//open the file and append. Create if not there.
f = fopen("tmp.log", "a+");
if (f == NULL) { printf("Something is wrong");}
struct tm *p;
struct tm buf;
char timestring[100];
time_t ltime = time(NULL);
if (NULL != (p=localtime_r(<ime, &buf))){
strftime(timestring, sizeof(timestring),"** %c: ", p);
fprintf(f, "%s %s \n", timestring, user_input);
}
fclose(f);
char* separator = " ";
char* argv[64];
int argc = 0;
char* tmp;
argv[argc] = strtok_r(user_input, separator, &tmp);
while( argv[argc] != NULL){
argc+=1;
argv[argc] = strtok_r(NULL, separator, &tmp);
}
printf("ABC"); //why doesn't this print??
execvp(argv[0],argv);
}
else{
wait(&state_loc);
}
}
int main ()
{
while(1)
{
char user_input[1024];
printf("recsh>> ");
//empty the buffer right scanf
scanf("%[^\n]", user_input);
//calls each character in the user input, repeat until it reaches the terminating \n
while( getchar() != '\n');
if(strcmp(user_input, "exit") == 0){
printf("Exiting\n");
break;
}
else{
execute(user_input);
}
}
return 0;
}