forked from drewwalton19216801/rush-sh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync_exec.rs
More file actions
960 lines (832 loc) · 32.2 KB
/
async_exec.rs
File metadata and controls
960 lines (832 loc) · 32.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
//! Asynchronous command execution module for background job control.
//!
//! This module handles the execution of commands in the background using the `&` operator,
//! including proper process group management, stdin redirection, and job table updates.
use std::fs::File;
use std::os::unix::io::{FromRawFd, IntoRawFd};
use std::os::unix::process::CommandExt;
use std::process::{Command, Stdio};
use crate::parser::{Ast, ShellCommand};
use crate::state::{Job, ShellState};
use super::expansion::{expand_variables_in_args, expand_wildcards};
use super::redirection::apply_redirections;
/// Execute an AST node asynchronously (in the background).
///
/// This function spawns the command in the background with proper process group setup,
/// redirects stdin to /dev/null, creates a job entry in the job table, and prints
/// a job notification. Returns 0 immediately without waiting for the command to complete.
///
/// # Arguments
///
/// * `ast` - The AST node to execute asynchronously
/// * `shell_state` - Mutable reference to the shell state
///
/// # Returns
///
/// Always returns 0 (background jobs don't block)
pub fn execute_async(ast: Ast, shell_state: &mut ShellState) -> i32 {
match ast {
Ast::Pipeline(commands) => {
if commands.is_empty() {
return 0;
}
// For single commands, check if it's a builtin
if commands.len() == 1 {
let cmd = &commands[0];
// Handle compound commands (subshells, etc.)
if let Some(ref compound) = cmd.compound {
let description = match compound.as_ref() {
Ast::Subshell { .. } => "subshell",
Ast::CommandGroup { .. } => "command group",
Ast::If { .. } => "if statement",
Ast::For { .. } => "for loop",
Ast::While { .. } => "while loop",
Ast::Until { .. } => "until loop",
Ast::Case { .. } => "case statement",
_ => "compound command",
};
return execute_compound_async(*compound.clone(), description, shell_state);
}
if cmd.args.is_empty() {
return 0;
}
// Expand variables and wildcards
let var_expanded_args = expand_variables_in_args(&cmd.args, shell_state);
let expanded_args = match expand_wildcards(&var_expanded_args, shell_state) {
Ok(args) => args,
Err(_) => return 1,
};
if expanded_args.is_empty() {
return 0;
}
// Check if it's a builtin command
if crate::builtins::is_builtin(&expanded_args[0]) {
// Execute builtin in background by forking
// Pass the already-expanded arguments to prevent double expansion
return execute_builtin_async(cmd, shell_state, Some(expanded_args));
}
}
// External command or pipeline - execute in background
execute_external_async(&commands, shell_state)
}
// Handle other AST types asynchronously by forking
Ast::Subshell { .. } => execute_compound_async(ast, "subshell", shell_state),
Ast::CommandGroup { .. } => execute_compound_async(ast, "command group", shell_state),
Ast::If { .. } => execute_compound_async(ast, "if statement", shell_state),
Ast::For { .. } => execute_compound_async(ast, "for loop", shell_state),
Ast::While { .. } => execute_compound_async(ast, "while loop", shell_state),
Ast::Until { .. } => execute_compound_async(ast, "until loop", shell_state),
Ast::Case { .. } => execute_compound_async(ast, "case statement", shell_state),
_ => {
// For other AST types (assignments, etc.), execute synchronously
// These don't make sense to run in background
super::execute(ast, shell_state)
}
}
}
/// Execute a compound command (subshell, command group, control structure) asynchronously.
///
/// This function forks a child process to execute the compound command in the background,
/// similar to how builtin commands are executed asynchronously.
///
/// # Arguments
///
/// * `ast` - The AST node to execute asynchronously
/// * `description` - A human-readable description of the command type (for job display)
/// * `shell_state` - Mutable reference to the shell state
///
/// # Returns
///
/// 0 on success, 1 on error
fn execute_compound_async(ast: Ast, description: &str, shell_state: &mut ShellState) -> i32 {
// Format command string for job display
let command_str = format!("{} &", description);
// Fork to execute compound command in background
unsafe {
let pid = libc::fork();
if pid < 0 {
// Fork failed
if shell_state.colors_enabled {
eprintln!(
"{}Failed to fork for background {}\x1b[0m",
shell_state.color_scheme.error, description
);
} else {
eprintln!("Failed to fork for background {}", description);
}
1
} else if pid == 0 {
// Child process
// Create new process group
let child_pid = libc::getpid();
libc::setpgid(child_pid, child_pid);
// Redirect stdin to /dev/null
let dev_null = libc::open(b"/dev/null\0".as_ptr() as *const i8, libc::O_RDONLY);
if dev_null >= 0 {
libc::dup2(dev_null, 0);
libc::close(dev_null);
}
// Execute the compound command
let exit_code = super::execute(ast, shell_state);
// Exit the child process
libc::_exit(exit_code);
} else {
// Parent process
let pid_u32 = pid as u32;
// Allocate job ID and create job entry
let job_id = shell_state.job_table.borrow_mut().allocate_job_id();
let job = Job::new(
job_id,
Some(pid_u32), // pgid is same as pid for single-process job
command_str.clone(),
vec![pid_u32],
false, // not a builtin (it's a compound command)
);
// Print job notification: [job_id] pid
println!("[{}] {}", job_id, pid_u32);
// Add job to job table
shell_state.job_table.borrow_mut().add_job(job);
// Set $! to the PID of the background process
shell_state.last_background_pid = Some(pid_u32);
0
}
}
}
/// Execute a builtin command asynchronously by forking a child process.
///
/// Since builtins run in the shell's process, we need to fork to run them
/// in the background. The child process executes the builtin and exits,
/// while the parent creates a job entry and returns immediately.
///
/// # Arguments
///
/// * `cmd` - The shell command to execute (must be a builtin)
/// * `shell_state` - Mutable reference to the shell state
/// * `pre_expanded_args` - Optional pre-expanded arguments to avoid double expansion
///
/// # Returns
///
/// 0 on success, 1 on error
pub fn execute_builtin_async(
cmd: &ShellCommand,
shell_state: &mut ShellState,
pre_expanded_args: Option<Vec<String>>,
) -> i32 {
// Use pre-expanded arguments if provided, otherwise expand them here
let expanded_args = if let Some(args) = pre_expanded_args {
args
} else {
// Expand arguments
let var_expanded_args = expand_variables_in_args(&cmd.args, shell_state);
match expand_wildcards(&var_expanded_args, shell_state) {
Ok(args) => args,
Err(_) => return 1,
}
};
if expanded_args.is_empty() {
return 0;
}
// Format command string for job display
let command_str = format_command_string(&expanded_args);
// Fork to execute builtin in background
unsafe {
let pid = libc::fork();
if pid < 0 {
// Fork failed
if shell_state.colors_enabled {
eprintln!(
"{}Failed to fork for background builtin\x1b[0m",
shell_state.color_scheme.error
);
} else {
eprintln!("Failed to fork for background builtin");
}
1
} else if pid == 0 {
// Child process
// Create new process group
let child_pid = libc::getpid();
libc::setpgid(child_pid, child_pid);
// Redirect stdin to /dev/null
let dev_null = libc::open(b"/dev/null\0".as_ptr() as *const i8, libc::O_RDONLY);
if dev_null >= 0 {
libc::dup2(dev_null, 0);
libc::close(dev_null);
}
// Execute the builtin
let temp_cmd = ShellCommand {
args: expanded_args,
redirections: cmd.redirections.clone(),
compound: None,
};
let exit_code = crate::builtins::execute_builtin(&temp_cmd, shell_state, None);
// Exit the child process
libc::_exit(exit_code);
} else {
// Parent process
let pid_u32 = pid as u32;
// Allocate job ID and create job entry
let job_id = shell_state.job_table.borrow_mut().allocate_job_id();
let job = Job::new(
job_id,
Some(pid_u32), // pgid is same as pid for single-process job
command_str.clone(),
vec![pid_u32],
true, // is_builtin
);
// Print job notification: [job_id] pid
println!("[{}] {}", job_id, pid_u32);
// Add job to job table
shell_state.job_table.borrow_mut().add_job(job);
// Set $! to the PID of the background process
shell_state.last_background_pid = Some(pid_u32);
0
}
}
}
/// Execute a builtin command as part of a background pipeline.
///
/// This function forks a child process to execute the builtin command,
/// properly handling pipeline I/O and process group management.
///
/// # Arguments
///
/// * `expanded_args` - The already-expanded command arguments
/// * `redirections` - Redirections to apply to the builtin command
/// * `stdin` - Optional stdin file from previous pipeline stage
/// * `is_first` - Whether this is the first command in the pipeline
/// * `is_last` - Whether this is the last command in the pipeline
/// * `pgid` - Optional process group ID to join
/// * `shell_state` - Mutable reference to the shell state
///
/// # Returns
///
/// Result containing (PID, optional stdout file for next stage) or error message
fn execute_builtin_in_background_pipeline(
expanded_args: &[String],
redirections: &[crate::parser::Redirection],
stdin: Option<File>,
is_first: bool,
is_last: bool,
pgid: Option<u32>,
shell_state: &mut ShellState,
) -> Result<(u32, Option<File>), String> {
use std::os::unix::io::AsRawFd;
// Create pipe for stdout if not last command
let (read_fd, write_fd) = if !is_last {
let (reader, writer) =
std::io::pipe().map_err(|e| format!("Failed to create pipe: {}", e))?;
(Some(reader), Some(writer))
} else {
(None, None)
};
unsafe {
let pid = libc::fork();
if pid < 0 {
return Err("Failed to fork for builtin command".to_string());
}
if pid == 0 {
// Child process
// Set process group
let child_pid = libc::getpid();
if let Some(group_id) = pgid {
libc::setpgid(child_pid, group_id as i32);
} else {
libc::setpgid(child_pid, child_pid);
}
// Setup stdin
if let Some(stdin_file) = stdin {
libc::dup2(stdin_file.as_raw_fd(), 0);
} else if is_first {
// First command - redirect stdin to /dev/null
let dev_null = libc::open(b"/dev/null\0".as_ptr() as *const i8, libc::O_RDONLY);
if dev_null >= 0 {
libc::dup2(dev_null, 0);
libc::close(dev_null);
}
}
// Setup stdout and save the pipe write end fd if present
let pipe_write_fd = if let Some(writer) = write_fd {
let write_raw_fd = writer.into_raw_fd();
libc::dup2(write_raw_fd, 1);
Some(write_raw_fd)
} else {
None
};
// Apply redirections
if let Err(e) = super::redirection::apply_redirections(redirections, shell_state, None)
{
eprintln!("Redirection error: {}", e);
libc::_exit(1);
}
// If stdout was redirected, close the pipe write end to prevent blocking downstream
if let Some(pipe_fd) = pipe_write_fd {
// Check if fd 1 was redirected by comparing the actual backing FD
let fd_table = shell_state.fd_table.borrow();
let current_stdout_fd = fd_table.get_raw_fd(1);
drop(fd_table);
// If fd 1 no longer points to pipe_fd (redirected or closed), close the pipe
let stdout_redirected = current_stdout_fd != Some(pipe_fd);
if stdout_redirected {
// Close the pipe write end since stdout is no longer using it
libc::close(pipe_fd);
}
}
// Execute the builtin
let temp_cmd = ShellCommand {
args: expanded_args.to_vec(),
redirections: redirections.to_vec(),
compound: None,
};
let exit_code = crate::builtins::execute_builtin(&temp_cmd, shell_state, None);
// Exit the child process
libc::_exit(exit_code);
}
let pid_u32 = pid as u32;
drop(write_fd);
let next_stdout = if let Some(reader) = read_fd {
Some(File::from_raw_fd(reader.into_raw_fd()))
} else {
None
};
Ok((pid_u32, next_stdout))
}
}
/// Execute a compound command as part of a background pipeline.
///
/// This function forks a child process to execute the compound command,
/// properly handling pipeline I/O and process group management.
///
/// # Arguments
///
/// * `compound_ast` - The compound command AST to execute
/// * `redirections` - Redirections to apply to the compound command
/// * `stdin` - Optional stdin file from previous pipeline stage
/// * `is_first` - Whether this is the first command in the pipeline
/// * `is_last` - Whether this is the last command in the pipeline
/// * `pgid` - Optional process group ID to join
/// * `shell_state` - Mutable reference to the shell state
///
/// # Returns
///
/// Result containing (PID, optional stdout file for next stage) or error message
fn execute_compound_in_background_pipeline(
compound_ast: &Ast,
redirections: &[crate::parser::Redirection],
stdin: Option<File>,
is_first: bool,
is_last: bool,
pgid: Option<u32>,
shell_state: &mut ShellState,
) -> Result<(u32, Option<File>), String> {
use std::os::unix::io::AsRawFd;
// Create pipe for stdout if not last command
let (read_fd, write_fd) = if !is_last {
let (reader, writer) =
std::io::pipe().map_err(|e| format!("Failed to create pipe: {}", e))?;
(Some(reader), Some(writer))
} else {
(None, None)
};
unsafe {
let pid = libc::fork();
if pid < 0 {
return Err("Failed to fork for compound command".to_string());
}
if pid == 0 {
// Child process
// Set process group
let child_pid = libc::getpid();
if let Some(group_id) = pgid {
libc::setpgid(child_pid, group_id as i32);
} else {
libc::setpgid(child_pid, child_pid);
}
// Setup stdin
if let Some(stdin_file) = stdin {
libc::dup2(stdin_file.as_raw_fd(), 0);
} else if is_first {
// First command - redirect stdin to /dev/null
let dev_null = libc::open(b"/dev/null\0".as_ptr() as *const i8, libc::O_RDONLY);
if dev_null >= 0 {
libc::dup2(dev_null, 0);
libc::close(dev_null);
}
}
// Setup stdout and save the pipe write end fd if present
let pipe_write_fd = if let Some(writer) = write_fd {
let write_raw_fd = writer.into_raw_fd();
libc::dup2(write_raw_fd, 1);
Some(write_raw_fd)
} else {
None
};
// Apply redirections
if let Err(e) = super::redirection::apply_redirections(redirections, shell_state, None)
{
eprintln!("Redirection error: {}", e);
libc::_exit(1);
}
// If stdout was redirected, close the pipe write end to prevent blocking downstream
if let Some(pipe_fd) = pipe_write_fd {
// Check if fd 1 was redirected by comparing the actual backing FD
let fd_table = shell_state.fd_table.borrow();
let current_stdout_fd = fd_table.get_raw_fd(1);
drop(fd_table);
// If fd 1 no longer points to pipe_fd (redirected or closed), close the pipe
let stdout_redirected = current_stdout_fd != Some(pipe_fd);
if stdout_redirected {
// Close the pipe write end since stdout is no longer using it
libc::close(pipe_fd);
}
}
// Execute the compound command
let exit_code = super::execute(compound_ast.clone(), shell_state);
// Exit the child process
libc::_exit(exit_code);
}
let pid_u32 = pid as u32;
drop(write_fd);
let next_stdout = if let Some(reader) = read_fd {
Some(File::from_raw_fd(reader.into_raw_fd()))
} else {
None
};
Ok((pid_u32, next_stdout))
}
}
/// Execute external commands or pipelines asynchronously.
///
/// Spawns the command(s) in the background with proper process group setup,
/// redirects stdin to /dev/null, creates job entries, and prints notifications.
///
/// # Arguments
///
/// * `commands` - The pipeline of commands to execute
/// * `shell_state` - Mutable reference to the shell state
///
/// # Returns
///
/// 0 on success, 1 on error
fn execute_external_async(commands: &[ShellCommand], shell_state: &mut ShellState) -> i32 {
// For pipelines, we need to spawn all commands and track their PIDs
let mut pids = Vec::new();
let mut previous_stdout: Option<File> = None;
let mut pgid: Option<u32> = None;
// Build command string for job display
let command_str = format_pipeline_string(commands);
for (i, cmd) in commands.iter().enumerate() {
let is_last = i == commands.len() - 1;
// Handle compound commands (subshells, etc.)
if let Some(ref compound) = cmd.compound {
// Warn about compound commands in background pipelines
if shell_state.colors_enabled {
eprintln!(
"{}Warning: Compound command in background pipeline - executing via fork\x1b[0m",
shell_state.color_scheme.error
);
} else {
eprintln!("Warning: Compound command in background pipeline - executing via fork");
}
// Execute compound command in background by forking
match execute_compound_in_background_pipeline(
compound.as_ref(),
&cmd.redirections,
previous_stdout.take(),
i == 0,
is_last,
pgid,
shell_state,
) {
Ok((pid, stdout)) => {
pids.push(pid);
// Set pgid to first process's PID
if pgid.is_none() {
pgid = Some(pid);
}
// Save stdout for next command if not last
if !is_last {
previous_stdout = stdout;
}
}
Err(e) => {
if shell_state.colors_enabled {
eprintln!(
"{}Error executing compound command in pipeline: {}\x1b[0m",
shell_state.color_scheme.error, e
);
} else {
eprintln!("Error executing compound command in pipeline: {}", e);
}
// Cleanup: kill any already-spawned processes
unsafe {
if let Some(group_id) = pgid {
// Kill the entire process group
libc::killpg(group_id as i32, libc::SIGKILL);
} else {
// Kill individual processes
for &pid in &pids {
libc::kill(pid as i32, libc::SIGKILL);
}
}
}
// Close previous_stdout if present
drop(previous_stdout);
// Clear pids and pgid so no job entry is created
pids.clear();
return 1;
}
}
continue;
}
if cmd.args.is_empty() {
continue;
}
// Expand variables and wildcards
let var_expanded_args = expand_variables_in_args(&cmd.args, shell_state);
let expanded_args = match expand_wildcards(&var_expanded_args, shell_state) {
Ok(args) => args,
Err(_) => return 1,
};
if expanded_args.is_empty() {
continue;
}
// Check if it's a builtin command
if crate::builtins::is_builtin(&expanded_args[0]) {
// Execute builtin in background pipeline by forking
match execute_builtin_in_background_pipeline(
&expanded_args,
&cmd.redirections,
previous_stdout.take(),
i == 0,
is_last,
pgid,
shell_state,
) {
Ok((pid, stdout)) => {
pids.push(pid);
// Set pgid to first process's PID
if pgid.is_none() {
pgid = Some(pid);
}
// Save stdout for next command if not last
if !is_last {
previous_stdout = stdout;
}
}
Err(e) => {
if shell_state.colors_enabled {
eprintln!(
"{}Error executing builtin command in pipeline: {}\x1b[0m",
shell_state.color_scheme.error, e
);
} else {
eprintln!("Error executing builtin command in pipeline: {}", e);
}
// Cleanup: kill any already-spawned processes
unsafe {
if let Some(group_id) = pgid {
// Kill the entire process group
libc::killpg(group_id as i32, libc::SIGKILL);
} else {
// Kill individual processes
for &pid in &pids {
libc::kill(pid as i32, libc::SIGKILL);
}
}
}
// Close previous_stdout if present
drop(previous_stdout);
// Clear pids and pgid so no job entry is created
pids.clear();
return 1;
}
}
continue;
}
// Prepare command
let mut command = Command::new(&expanded_args[0]);
command.args(&expanded_args[1..]);
// Set environment for child process
let child_env = shell_state.get_env_for_child();
command.env_clear();
for (key, value) in child_env {
command.env(key, value);
}
// Set stdin
if let Some(prev) = previous_stdout.take() {
// Use output from previous command in pipeline
command.stdin(Stdio::from(prev));
} else if i == 0 {
// First command in pipeline - redirect stdin to /dev/null
command.stdin(Stdio::null());
} else {
// Should not happen, but handle gracefully
command.stdin(Stdio::null());
}
// Set stdout for next command in pipeline
if !is_last {
command.stdout(Stdio::piped());
}
// Apply redirections for this command
if let Err(e) = apply_redirections(&cmd.redirections, shell_state, Some(&mut command)) {
if shell_state.colors_enabled {
eprintln!(
"{}Redirection error: {}\x1b[0m",
shell_state.color_scheme.error, e
);
} else {
eprintln!("Redirection error: {}", e);
}
// Cleanup: kill any already-spawned processes
unsafe {
if let Some(group_id) = pgid {
// Kill the entire process group
libc::killpg(group_id as i32, libc::SIGKILL);
} else {
// Kill individual processes
for &pid in &pids {
libc::kill(pid as i32, libc::SIGKILL);
}
}
}
// Close previous_stdout if present
drop(previous_stdout);
// Clear pids and pgid so no job entry is created
pids.clear();
return 1;
}
// Set up process group using pre_exec
let current_pgid = pgid;
unsafe {
command.pre_exec(move || {
let pid = libc::getpid();
// Set process group
if let Some(group_id) = current_pgid {
// Join existing process group (for pipeline)
libc::setpgid(pid, group_id as i32);
} else {
// Create new process group (first process in pipeline)
libc::setpgid(pid, pid);
}
Ok(())
});
}
// Spawn the command
match command.spawn() {
Ok(mut child) => {
let pid = child.id();
pids.push(pid);
// Set pgid to first process's PID
if pgid.is_none() {
pgid = Some(pid);
}
// If not last command, save stdout for next command
if !is_last {
previous_stdout = child
.stdout
.take()
.map(|s| unsafe { File::from_raw_fd(s.into_raw_fd()) });
}
// Don't wait for the child - it runs in background
}
Err(e) => {
if shell_state.colors_enabled {
eprintln!(
"{}Error spawning command '{}': {}\x1b[0m",
shell_state.color_scheme.error, expanded_args[0], e
);
} else {
eprintln!("Error spawning command '{}': {}", expanded_args[0], e);
}
// Cleanup: kill any already-spawned processes
unsafe {
if let Some(group_id) = pgid {
// Kill the entire process group
libc::killpg(group_id as i32, libc::SIGKILL);
} else {
// Kill individual processes
for &pid in &pids {
libc::kill(pid as i32, libc::SIGKILL);
}
}
}
// Close previous_stdout if present
drop(previous_stdout);
// Clear pids and pgid so no job entry is created
pids.clear();
return 1;
}
}
}
if pids.is_empty() {
return 0;
}
// Allocate job ID and create job entry
let job_id = shell_state.job_table.borrow_mut().allocate_job_id();
let job = Job::new(
job_id,
pgid,
command_str,
pids.clone(),
false, // not a builtin
);
// Print job notification: [job_id] pid
// For pipelines, print the first PID (process group leader)
println!("[{}] {}", job_id, pids[0]);
// Add job to job table
shell_state.job_table.borrow_mut().add_job(job);
// Set $! to the PID of the last process in the pipeline (or the only process)
// This matches POSIX behavior where $! is the PID of the last process in a background pipeline
if let Some(&last_pid) = pids.last() {
shell_state.last_background_pid = Some(last_pid);
}
0
}
/// Format a command's arguments into a display string.
///
/// # Arguments
///
/// * `args` - The command arguments
///
/// # Returns
///
/// A formatted command string
fn format_command_string(args: &[String]) -> String {
args.join(" ")
}
/// Format a pipeline of commands into a display string.
///
/// # Arguments
///
/// * `commands` - The pipeline of commands
///
/// # Returns
///
/// A formatted pipeline string
fn format_pipeline_string(commands: &[ShellCommand]) -> String {
let mut parts = Vec::new();
for cmd in commands {
if let Some(ref compound) = cmd.compound {
// For compound commands, use a simplified representation
match compound.as_ref() {
Ast::Subshell { .. } => parts.push("(...)".to_string()),
Ast::CommandGroup { .. } => parts.push("{...}".to_string()),
_ => parts.push("compound".to_string()),
}
} else if !cmd.args.is_empty() {
// Use original unexpanded command as typed by the user
parts.push(cmd.args.join(" "));
}
}
parts.join(" | ")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_format_command_string() {
let args = vec!["echo".to_string(), "hello".to_string(), "world".to_string()];
assert_eq!(format_command_string(&args), "echo hello world");
}
#[test]
fn test_format_pipeline_string() {
let commands = vec![
ShellCommand {
args: vec!["ls".to_string(), "-la".to_string()],
redirections: vec![],
compound: None,
},
ShellCommand {
args: vec!["grep".to_string(), "txt".to_string()],
redirections: vec![],
compound: None,
},
];
assert_eq!(
format_pipeline_string(&commands),
"ls -la | grep txt"
);
}
#[test]
fn test_format_pipeline_with_subshell() {
let commands = vec![
ShellCommand {
args: vec![],
redirections: vec![],
compound: Some(Box::new(Ast::Subshell {
body: Box::new(Ast::Pipeline(vec![])),
})),
},
ShellCommand {
args: vec!["grep".to_string(), "txt".to_string()],
redirections: vec![],
compound: None,
},
];
assert_eq!(
format_pipeline_string(&commands),
"(...) | grep txt"
);
}
}