Skip to content

Commit 38caa9f

Browse files
author
hyqooo
committed
Background processing work
But now we can't stop processes that works in the background
1 parent 6560c2c commit 38caa9f

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

shell.c

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ char **args_proc(char *, struct tokens *);
5252

5353
int redirection(char *, int);
5454
void child_sig_handler();
55+
void put_process_in_foreground(int);
5556

5657
const int MAX_PATH_SIZE = 128;
5758

@@ -106,12 +107,6 @@ int cmd_cd(struct tokens *tokens){
106107
}
107108

108109
/* Execute program */
109-
/*
110-
Signal handling.
111-
1. I need to separate all subprocesses into their own pgids(process group ids)
112-
2. Set current subprocess on the foreground (assumed that only latest process goes to foreground)
113-
3. Properly handle all receiving signal they must affect only on the foreground processes.
114-
*/
115110
int shell_exec(struct tokens *tokens){
116111
/* saves descriptors associated with stdout and stdin */
117112
int saved_stdout = dup(fileno(stdout));
@@ -124,17 +119,13 @@ int shell_exec(struct tokens *tokens){
124119
if (!path || !args) return -1;
125120

126121
pid_t cpid;
127-
int status;
128122
cpid = fork();
129123
/* cpid > 0 - parent process, cpid == 0 - child process, cpid < 0 - error */
130124
if (cpid > 0) {
131125
/* set children process to foreground */
132126
setpgid(cpid, 0);
133-
tcsetpgrp(0, cpid);
134-
135-
waitpid(-1, &status, WUNTRACED);
136-
/* return shell to the foreground */
137-
tcsetpgrp(0, getpid());
127+
if (strcmp(tokens_get_token(tokens, tokens->tokens_length - 1), "&"))
128+
put_process_in_foreground(cpid);
138129
} else if (cpid == 0){
139130
child_sig_handler();
140131
/* create new session for background processing */
@@ -157,6 +148,18 @@ int shell_exec(struct tokens *tokens){
157148
return 1;
158149
}
159150

151+
void put_process_in_foreground(int pid){
152+
int status;
153+
/* put the process with specified id in the foreground. */
154+
tcsetpgrp(STDIN_FILENO, pid);
155+
156+
/* wait until it is done */
157+
waitpid(-1, &status, WUNTRACED);
158+
159+
/* Put the shell back in the foreground. */
160+
tcsetpgrp(STDIN_FILENO, getpid());
161+
}
162+
160163
void child_sig_handler(){
161164
signal(SIGINT, SIG_DFL);
162165
signal(SIGTSTP, SIG_DFL);

0 commit comments

Comments
 (0)