Im trying to make my own shell in C, but Im having trouble with handling background and foreground processes. Here is where I create processes:
void call_exec(char *cmd) { pid_t cpid; is_Background(); if(index(cmd, '/') == NULL) { int i; printf("cmd is %s\n", cmd); cpid = fork(); if(cpid == 0) { i = execvp(cmd, my_argv); if(i < 0) { printf("%s: %s\n", cmd, "command not found"); exit(1); } } else { if(!is_BG ) { wait(NULL); } is_BG = 0; } } is_Background:
void is_Background() { if(strcmp(my_argv[arg_index], "&") == 0) { is_BG = 1; my_argv[arg_index] = NULL; } } When I run my code and enter "gedit" in command line, shell waits until I close gedit window and then prompts me to enter new command. When I enter "gedit &" to run gedit in the background, it just works fine, gedit window opens and shell immediately prompts me to enter new command without waiting to close gedit window. The problem is, after I use "&" with any command only once, shell never waits for any foreground processes to end/close. Ex, if I enter "gedit" or "firefox" without "&" , shell doesn't wait for them to close.
I hope I was able to explain my problem properly, my English isn't that good, so sorry for mistakes. If I need to provide more information please tell me. Thanks.