3

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.

1 Answer 1

2

There are two issues here:

First of all, gedit and firefox are single instance programs. Any other invocations will just reuse the existing instance. You see the same thing in bash:

bash$ gedit & # Starts gedit and returns immediately bash$ gedit # Opens a new tab in the existing window and returns immediately 

You should test with multiple instance programs like xterm or xeyes instead.

Secondly, your wait(NULL) call waits for any process to close, not necessarily the last one. In your shell, you'd probably see this:

yourshell$ xterm & # starts xterms and returns immediately. # Now close the xterm before running the next command yourshell$ xeyes # starts xeyes, waits on xterm, returns immediately 

You can instead use waitpid(cpid, NULL, 0) to wait for the correct process.

Sign up to request clarification or add additional context in comments.

2 Comments

I was wondering how I could test it and the first thing came to my mind was gedit. Thank you so much for your help.
@thatotherguy waitpid(cpid, NULL, 0) why the status argument is NULL?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.