@@ -52,6 +52,7 @@ char **args_proc(char *, struct tokens *);
52
52
53
53
int redirection (char * , int );
54
54
void child_sig_handler ();
55
+ void put_process_in_foreground (int );
55
56
56
57
const int MAX_PATH_SIZE = 128 ;
57
58
@@ -106,12 +107,6 @@ int cmd_cd(struct tokens *tokens){
106
107
}
107
108
108
109
/* 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
- */
115
110
int shell_exec (struct tokens * tokens ){
116
111
/* saves descriptors associated with stdout and stdin */
117
112
int saved_stdout = dup (fileno (stdout ));
@@ -124,17 +119,13 @@ int shell_exec(struct tokens *tokens){
124
119
if (!path || !args ) return -1 ;
125
120
126
121
pid_t cpid ;
127
- int status ;
128
122
cpid = fork ();
129
123
/* cpid > 0 - parent process, cpid == 0 - child process, cpid < 0 - error */
130
124
if (cpid > 0 ) {
131
125
/* set children process to foreground */
132
126
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 );
138
129
} else if (cpid == 0 ){
139
130
child_sig_handler ();
140
131
/* create new session for background processing */
@@ -157,6 +148,18 @@ int shell_exec(struct tokens *tokens){
157
148
return 1 ;
158
149
}
159
150
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
+
160
163
void child_sig_handler (){
161
164
signal (SIGINT , SIG_DFL );
162
165
signal (SIGTSTP , SIG_DFL );
0 commit comments