fcoreutils 0.22.0

High-performance GNU coreutils replacement with SIMD and parallelism
Documentation
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
#[cfg(not(unix))]
fn main() {
    eprintln!("timeout: only available on Unix");
    std::process::exit(1);
}

// ftimeout -- run a command with a time limit
//
// Usage: timeout [OPTION] DURATION COMMAND [ARG]...

#[cfg(unix)]
use std::process;

#[cfg(unix)]
const TOOL_NAME: &str = "timeout";
#[cfg(unix)]
const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Exit code when the command times out.
#[cfg(unix)]
const EXIT_TIMEOUT: i32 = 124;
/// Exit code when timeout itself fails.
#[cfg(unix)]
const EXIT_FAILURE: i32 = 125;
/// Exit code when the command cannot be executed.
#[cfg(unix)]
const EXIT_CANNOT_INVOKE: i32 = 126;
/// Exit code when the command is not found.
#[cfg(unix)]
const EXIT_ENOENT: i32 = 127;

#[cfg(unix)]
fn main() {
    coreutils_rs::common::reset_sigpipe();

    let args: Vec<String> = std::env::args().skip(1).collect();

    let mut signal_name = "TERM".to_string();
    let mut kill_after: Option<f64> = None;
    let mut foreground = false;
    let mut preserve_status = false;
    let mut verbose = false;
    let mut positional_start: Option<usize> = None;

    let mut i = 0;
    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            "--help" => {
                println!("Usage: {} [OPTION] DURATION COMMAND [ARG]...", TOOL_NAME);
                println!("Start COMMAND, and kill it if still running after DURATION.");
                println!();
                println!("  -s, --signal=SIGNAL    specify the signal to be sent on timeout;");
                println!("                           SIGNAL may be a name like 'HUP' or a number;");
                println!("                           see 'kill -l' for a list of signals");
                println!("  -k, --kill-after=DURATION");
                println!(
                    "                         also send a KILL signal if COMMAND is still running"
                );
                println!("                           this long after the initial signal was sent");
                println!(
                    "      --foreground       when not running timeout directly from a shell prompt,"
                );
                println!(
                    "                           allow COMMAND to read from the TTY and get TTY signals"
                );
                println!(
                    "      --preserve-status  exit with the same status as COMMAND, even when the"
                );
                println!("                           command times out");
                println!(
                    "  -v, --verbose          diagnose to stderr any signal sent upon timeout"
                );
                println!("      --help             display this help and exit");
                println!("      --version          output version information and exit");
                println!();
                println!("DURATION is a floating point number with an optional suffix:");
                println!(
                    "'s' for seconds (the default), 'm' for minutes, 'h' for hours or 'd' for days."
                );
                println!("A duration of 0 disables the associated timeout.");
                println!();
                println!(
                    "If the command times out, and --preserve-status is not set, then exit with"
                );
                println!("status 124.  Otherwise, exit with the status of COMMAND.  If no signal");
                println!("is specified, send the TERM signal upon timeout.  The TERM signal kills");
                println!(
                    "any process that does not block or catch that signal.  It may be necessary"
                );
                println!(
                    "to use the KILL (9) signal, since this signal cannot be caught, in which"
                );
                println!("case the exit status is 128+9 rather than 124.");
                return;
            }
            "--version" => {
                println!("{} (fcoreutils) {}", TOOL_NAME, VERSION);
                return;
            }
            "--foreground" => foreground = true,
            "--preserve-status" => preserve_status = true,
            "-v" | "--verbose" => verbose = true,
            s if s.starts_with("--signal=") => {
                signal_name = s["--signal=".len()..].to_string();
            }
            s if s.starts_with("--kill-after=") => {
                let val = &s["--kill-after=".len()..];
                kill_after = Some(parse_duration(val).unwrap_or_else(|| {
                    eprintln!("{}: invalid time interval '{}'", TOOL_NAME, val);
                    process::exit(EXIT_FAILURE);
                }));
            }
            "-s" | "--signal" => {
                i += 1;
                if i >= args.len() {
                    eprintln!("{}: option requires an argument -- 's'", TOOL_NAME);
                    process::exit(EXIT_FAILURE);
                }
                signal_name = args[i].clone();
            }
            "-k" | "--kill-after" => {
                i += 1;
                if i >= args.len() {
                    eprintln!("{}: option requires an argument -- 'k'", TOOL_NAME);
                    process::exit(EXIT_FAILURE);
                }
                kill_after = Some(parse_duration(&args[i]).unwrap_or_else(|| {
                    eprintln!("{}: invalid time interval '{}'", TOOL_NAME, args[i]);
                    process::exit(EXIT_FAILURE);
                }));
            }
            s if s.starts_with('-') && s.len() > 1 && !s.starts_with("--") => {
                let rest = &s[1..];
                let chars: Vec<char> = rest.chars().collect();
                let mut j = 0;
                while j < chars.len() {
                    match chars[j] {
                        'v' => verbose = true,
                        's' => {
                            if j + 1 < chars.len() {
                                signal_name = chars[j + 1..].iter().collect();
                                j = chars.len();
                                continue;
                            } else {
                                i += 1;
                                if i >= args.len() {
                                    eprintln!("{}: option requires an argument -- 's'", TOOL_NAME);
                                    process::exit(EXIT_FAILURE);
                                }
                                signal_name = args[i].clone();
                            }
                        }
                        'k' => {
                            if j + 1 < chars.len() {
                                let val: String = chars[j + 1..].iter().collect();
                                kill_after = Some(parse_duration(&val).unwrap_or_else(|| {
                                    eprintln!("{}: invalid time interval '{}'", TOOL_NAME, val);
                                    process::exit(EXIT_FAILURE);
                                }));
                                j = chars.len();
                                continue;
                            } else {
                                i += 1;
                                if i >= args.len() {
                                    eprintln!("{}: option requires an argument -- 'k'", TOOL_NAME);
                                    process::exit(EXIT_FAILURE);
                                }
                                kill_after = Some(parse_duration(&args[i]).unwrap_or_else(|| {
                                    eprintln!("{}: invalid time interval '{}'", TOOL_NAME, args[i]);
                                    process::exit(EXIT_FAILURE);
                                }));
                            }
                        }
                        _ => {
                            // This might be start of positional args
                            positional_start = Some(i);
                            break;
                        }
                    }
                    j += 1;
                }
                if positional_start.is_some() {
                    break;
                }
            }
            "--" => {
                i += 1;
                if i < args.len() {
                    positional_start = Some(i);
                }
                break;
            }
            _ => {
                positional_start = Some(i);
                break;
            }
        }
        i += 1;
    }

    let start = positional_start.unwrap_or_else(|| {
        eprintln!("{}: missing operand", TOOL_NAME);
        eprintln!("Try '{} --help' for more information.", TOOL_NAME);
        process::exit(EXIT_FAILURE);
    });

    if start >= args.len() {
        eprintln!("{}: missing operand", TOOL_NAME);
        eprintln!("Try '{} --help' for more information.", TOOL_NAME);
        process::exit(EXIT_FAILURE);
    }

    let duration = parse_duration(&args[start]).unwrap_or_else(|| {
        eprintln!("{}: invalid time interval '{}'", TOOL_NAME, args[start]);
        eprintln!("Try '{} --help' for more information.", TOOL_NAME);
        process::exit(EXIT_FAILURE);
    });

    if start + 1 >= args.len() {
        eprintln!("{}: missing operand", TOOL_NAME);
        eprintln!("Try '{} --help' for more information.", TOOL_NAME);
        process::exit(EXIT_FAILURE);
    }

    let command = &args[start + 1];
    let command_args: Vec<&str> = args[start + 2..].iter().map(|s| s.as_str()).collect();

    let sig = parse_signal(&signal_name).unwrap_or_else(|| {
        eprintln!("{}: invalid signal '{}'", TOOL_NAME, signal_name);
        process::exit(EXIT_FAILURE);
    });
    // Resolve to canonical name for verbose output (e.g. "9" -> "KILL")
    let signal_name = signal_number_to_name(sig)
        .map(|s| s.to_string())
        .unwrap_or(signal_name);

    // Fork
    let pid = unsafe { libc::fork() };
    if pid < 0 {
        eprintln!("{}: fork: {}", TOOL_NAME, std::io::Error::last_os_error());
        process::exit(EXIT_FAILURE);
    }

    if pid == 0 {
        // Child: exec the command
        if !foreground {
            // Put child in its own process group
            unsafe {
                libc::setpgid(0, 0);
            }
        }

        // Close inherited file descriptors above stderr.
        // Use close_range() syscall (Linux 5.9+) for O(1) instead of looping 1021 close() calls.
        #[cfg(target_os = "linux")]
        unsafe {
            // close_range(3, UINT_MAX, 0) — not yet in libc crate, use syscall directly
            libc::syscall(libc::SYS_close_range, 3u32, u32::MAX, 0u32);
        }
        #[cfg(not(target_os = "linux"))]
        {
            // Fallback: only close FDs we know are open via /dev/fd or a small range
            for fd in 3..64 {
                unsafe {
                    libc::close(fd);
                }
            }
        }

        let c_command =
            std::ffi::CString::new(command.as_str()).unwrap_or_else(|_| process::exit(EXIT_ENOENT));
        let mut c_args: Vec<std::ffi::CString> = Vec::with_capacity(command_args.len() + 1);
        c_args.push(c_command.clone());
        for a in &command_args {
            c_args.push(std::ffi::CString::new(*a).unwrap_or_else(|_| process::exit(EXIT_ENOENT)));
        }
        let c_argv: Vec<*const libc::c_char> = c_args
            .iter()
            .map(|s| s.as_ptr())
            .chain(std::iter::once(std::ptr::null()))
            .collect();

        unsafe {
            libc::execvp(c_command.as_ptr(), c_argv.as_ptr());
        }

        // If execvp returns, it failed
        let err = std::io::Error::last_os_error();
        let code = if err.kind() == std::io::ErrorKind::NotFound {
            EXIT_ENOENT
        } else {
            EXIT_CANNOT_INVOKE
        };
        eprintln!(
            "{}: failed to run command '{}': {}",
            TOOL_NAME,
            command,
            coreutils_rs::common::io_error_msg(&err)
        );
        process::exit(code);
    }

    // Parent: set up timeout
    let child_pid = pid;
    let target_pid = if foreground { child_pid } else { -child_pid };

    // Install signal handlers to forward signals to child
    unsafe {
        libc::signal(libc::SIGTERM, libc::SIG_IGN);
        libc::signal(libc::SIGINT, libc::SIG_IGN);
        libc::signal(libc::SIGHUP, libc::SIG_IGN);
    }

    // Wait for child with timeout using SIGALRM + blocking waitpid.
    // This is how GNU timeout works: set an alarm, then block in waitpid.
    // SIGCHLD wakes waitpid when child exits; SIGALRM wakes it on timeout.
    let mut timed_out = false;
    let mut status: libc::c_int = 0;

    // Install a no-op SIGALRM handler (so alarm interrupts waitpid with EINTR).
    unsafe {
        extern "C" fn sigalrm_handler(_: libc::c_int) {}
        let mut sa: libc::sigaction = std::mem::zeroed();
        sa.sa_sigaction = sigalrm_handler as *const () as usize;
        sa.sa_flags = 0; // No SA_RESTART — we WANT waitpid to be interrupted
        libc::sigemptyset(&mut sa.sa_mask);
        libc::sigaction(libc::SIGALRM, &sa, std::ptr::null_mut());
    }

    if duration > 0.0 {
        // Use setitimer for sub-second precision (alarm() is seconds only).
        let secs = duration as libc::time_t;
        let usecs = ((duration - secs as f64) * 1_000_000.0) as libc::suseconds_t;
        let itval = libc::itimerval {
            it_interval: libc::timeval {
                tv_sec: 0,
                tv_usec: 0,
            },
            it_value: libc::timeval {
                tv_sec: secs,
                tv_usec: usecs,
            },
        };
        unsafe {
            libc::setitimer(libc::ITIMER_REAL, &itval, std::ptr::null_mut());
        }
    }

    // Blocking wait — returns when child exits (SIGCHLD) or alarm fires (EINTR).
    loop {
        let ret = unsafe { libc::waitpid(child_pid, &mut status, 0) };
        if ret == child_pid {
            // Child exited before timeout
            break;
        }
        if ret < 0 {
            let err = std::io::Error::last_os_error();
            if err.kind() == std::io::ErrorKind::Interrupted {
                // Interrupted — check if child already exited
                let ret2 = unsafe { libc::waitpid(child_pid, &mut status, libc::WNOHANG) };
                if ret2 == child_pid {
                    break; // Child exited
                }
                // SIGALRM fired — timeout
                timed_out = true;
                if verbose {
                    eprintln!(
                        "{}: sending signal {} to command '{}'",
                        TOOL_NAME, signal_name, command
                    );
                }
                let kill_ret = unsafe { libc::kill(target_pid, sig) };
                if kill_ret != 0 {
                    let err = std::io::Error::last_os_error();
                    if err.raw_os_error() == Some(libc::ESRCH) {
                        timed_out = false;
                    }
                }
                break;
            }
            // Other error (ECHILD) — child no longer exists
            break;
        }
    }

    if timed_out {
        // Track the effective signal for exit status (may upgrade to SIGKILL
        // if kill-after fires).
        let mut effective_sig = sig;

        // Wait for child to die after the initial signal
        if let Some(kill_secs) = kill_after {
            // Poll until child exits or kill-after period elapses
            let kill_nanos = (kill_secs * 1_000_000_000.0) as u128;
            let kill_start = std::time::Instant::now();
            loop {
                let ret = unsafe { libc::waitpid(child_pid, &mut status, libc::WNOHANG) };
                if ret == child_pid || ret < 0 {
                    break;
                }
                if kill_start.elapsed().as_nanos() >= kill_nanos {
                    if verbose {
                        eprintln!(
                            "{}: sending signal KILL to command '{}'",
                            TOOL_NAME, command
                        );
                    }
                    let kill_ret = unsafe { libc::kill(target_pid, libc::SIGKILL) };
                    if kill_ret == 0 {
                        unsafe {
                            libc::waitpid(child_pid, &mut status, 0);
                        }
                    }
                    // The effective signal is now SIGKILL since kill-after fired
                    effective_sig = libc::SIGKILL;
                    break;
                }
                std::thread::sleep(std::time::Duration::from_millis(10));
            }
        } else {
            // No kill-after: blocking wait for child to exit after signal
            // This matches GNU timeout behavior
            unsafe {
                libc::waitpid(child_pid, &mut status, 0);
            }
        }

        if preserve_status {
            process::exit(status_to_code(status));
        } else {
            // Match GNU timeout: only re-raise uncatchable signals (SIGKILL)
            // so the parent sees a signal death. For all other signals,
            // exit with EXIT_TIMEOUT (124).
            if effective_sig == libc::SIGKILL {
                unsafe {
                    let mut unblock: libc::sigset_t = std::mem::zeroed();
                    libc::sigemptyset(&mut unblock);
                    libc::sigaddset(&mut unblock, effective_sig);
                    libc::sigprocmask(libc::SIG_UNBLOCK, &unblock, std::ptr::null_mut());
                    libc::kill(libc::getpid(), effective_sig);
                    loop {
                        libc::pause();
                    }
                }
            }
            process::exit(EXIT_TIMEOUT);
        }
    }

    // Child exited normally (before timeout)
    process::exit(status_to_code(status));
}

#[cfg(unix)]
fn status_to_code(status: libc::c_int) -> i32 {
    if libc::WIFEXITED(status) {
        libc::WEXITSTATUS(status)
    } else if libc::WIFSIGNALED(status) {
        128 + libc::WTERMSIG(status)
    } else {
        EXIT_FAILURE
    }
}

#[cfg(unix)]
fn parse_duration(s: &str) -> Option<f64> {
    if s.is_empty() {
        return None;
    }
    let (num, suffix) = if let Some(stripped) = s.strip_suffix('s') {
        (stripped, 's')
    } else if let Some(stripped) = s.strip_suffix('m') {
        (stripped, 'm')
    } else if let Some(stripped) = s.strip_suffix('h') {
        (stripped, 'h')
    } else if let Some(stripped) = s.strip_suffix('d') {
        (stripped, 'd')
    } else {
        (s, 's')
    };

    let value: f64 = num.parse().ok()?;
    if value < 0.0 {
        return None;
    }

    let multiplier = match suffix {
        's' => 1.0,
        'm' => 60.0,
        'h' => 3600.0,
        'd' => 86400.0,
        _ => return None,
    };

    Some(value * multiplier)
}

#[cfg(unix)]
fn parse_signal(name: &str) -> Option<libc::c_int> {
    // Try numeric first
    if let Ok(n) = name.parse::<libc::c_int>() {
        return Some(n);
    }

    // Strip SIG prefix if present
    let upper = name.to_uppercase();
    let sig_name = if let Some(stripped) = upper.strip_prefix("SIG") {
        stripped
    } else {
        &upper
    };

    match sig_name {
        "HUP" => Some(libc::SIGHUP),
        "INT" => Some(libc::SIGINT),
        "QUIT" => Some(libc::SIGQUIT),
        "ILL" => Some(libc::SIGILL),
        "TRAP" => Some(libc::SIGTRAP),
        "ABRT" | "IOT" => Some(libc::SIGABRT),
        "BUS" => Some(libc::SIGBUS),
        "FPE" => Some(libc::SIGFPE),
        "KILL" => Some(libc::SIGKILL),
        "USR1" => Some(libc::SIGUSR1),
        "SEGV" => Some(libc::SIGSEGV),
        "USR2" => Some(libc::SIGUSR2),
        "PIPE" => Some(libc::SIGPIPE),
        "ALRM" => Some(libc::SIGALRM),
        "TERM" => Some(libc::SIGTERM),
        "CHLD" => Some(libc::SIGCHLD),
        "CONT" => Some(libc::SIGCONT),
        "STOP" => Some(libc::SIGSTOP),
        "TSTP" => Some(libc::SIGTSTP),
        "TTIN" => Some(libc::SIGTTIN),
        "TTOU" => Some(libc::SIGTTOU),
        "URG" => Some(libc::SIGURG),
        "XCPU" => Some(libc::SIGXCPU),
        "XFSZ" => Some(libc::SIGXFSZ),
        "VTALRM" => Some(libc::SIGVTALRM),
        "PROF" => Some(libc::SIGPROF),
        "WINCH" => Some(libc::SIGWINCH),
        "IO" | "POLL" => Some(libc::SIGIO),
        "SYS" => Some(libc::SIGSYS),
        _ => None,
    }
}

#[cfg(unix)]
fn signal_number_to_name(sig: libc::c_int) -> Option<&'static str> {
    match sig {
        libc::SIGHUP => Some("HUP"),
        libc::SIGINT => Some("INT"),
        libc::SIGQUIT => Some("QUIT"),
        libc::SIGILL => Some("ILL"),
        libc::SIGTRAP => Some("TRAP"),
        libc::SIGABRT => Some("ABRT"),
        libc::SIGBUS => Some("BUS"),
        libc::SIGFPE => Some("FPE"),
        libc::SIGKILL => Some("KILL"),
        libc::SIGUSR1 => Some("USR1"),
        libc::SIGSEGV => Some("SEGV"),
        libc::SIGUSR2 => Some("USR2"),
        libc::SIGPIPE => Some("PIPE"),
        libc::SIGALRM => Some("ALRM"),
        libc::SIGTERM => Some("TERM"),
        libc::SIGCHLD => Some("CHLD"),
        libc::SIGCONT => Some("CONT"),
        libc::SIGSTOP => Some("STOP"),
        libc::SIGTSTP => Some("TSTP"),
        libc::SIGTTIN => Some("TTIN"),
        libc::SIGTTOU => Some("TTOU"),
        libc::SIGURG => Some("URG"),
        libc::SIGXCPU => Some("XCPU"),
        libc::SIGXFSZ => Some("XFSZ"),
        libc::SIGVTALRM => Some("VTALRM"),
        libc::SIGPROF => Some("PROF"),
        libc::SIGWINCH => Some("WINCH"),
        libc::SIGIO => Some("IO"),
        libc::SIGSYS => Some("SYS"),
        _ => None,
    }
}

#[cfg(all(test, unix))]
mod tests {
    use std::process::Command;

    fn cmd() -> Command {
        let mut path = std::env::current_exe().unwrap();
        path.pop();
        path.pop();
        path.push("ftimeout");
        Command::new(path)
    }

    #[test]
    fn test_command_completes_before_timeout() {
        let output = cmd().args(["10", "echo", "hello"]).output().unwrap();
        assert_eq!(output.status.code(), Some(0));
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert_eq!(stdout.trim(), "hello");
    }

    #[test]
    fn test_command_times_out() {
        let output = cmd().args(["0.1", "sleep", "10"]).output().unwrap();
        // Exit code should be 124 (timed out)
        assert_eq!(output.status.code(), Some(124));
    }

    #[test]
    fn test_kill_after() {
        let start = std::time::Instant::now();
        let output = cmd()
            .args(["-k", "0.1", "0.1", "sleep", "100"])
            .output()
            .unwrap();
        let elapsed = start.elapsed();
        // Should complete relatively quickly (timeout + kill_after)
        assert!(elapsed.as_secs() < 5, "Should not hang");
        // Exit code is 124 (timed out) or 137 (killed by SIGKILL = 128+9)
        let code = output.status.code().unwrap();
        assert!(
            code == 124 || code == 137,
            "Expected 124 or 137, got {}",
            code
        );
    }

    #[test]
    fn test_preserve_status() {
        let output = cmd()
            .args(["--preserve-status", "0.1", "sleep", "10"])
            .output()
            .unwrap();
        let code = output.status.code().unwrap();
        // With --preserve-status, should get the signal exit code, not 124
        // SIGTERM = 15, so 128 + 15 = 143
        assert_ne!(code, 124, "Should NOT be 124 with --preserve-status");
    }

    #[test]
    fn test_signal_flag() {
        let output = cmd()
            .args(["-s", "KILL", "0.1", "sleep", "10"])
            .output()
            .unwrap();
        // ftimeout re-raises the signal on itself (matching GNU timeout),
        // so the process dies by signal rather than exiting normally.
        #[cfg(unix)]
        {
            use std::os::unix::process::ExitStatusExt;
            let sig = output.status.signal();
            assert_eq!(sig, Some(9), "Expected signal 9 (SIGKILL), got {:?}", sig);
        }
        #[cfg(not(unix))]
        {
            let code = output.status.code().unwrap();
            assert_eq!(code, 137, "Expected 137 (128+SIGKILL), got {}", code);
        }
    }

    #[test]
    fn test_duration_with_suffix() {
        // 0.1s should work the same as 0.1
        let output = cmd().args(["0.1s", "sleep", "10"]).output().unwrap();
        assert_eq!(output.status.code(), Some(124));
    }

    #[test]
    fn test_zero_duration() {
        // Duration of 0 means no timeout
        let output = cmd().args(["0", "echo", "no timeout"]).output().unwrap();
        assert_eq!(output.status.code(), Some(0));
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert_eq!(stdout.trim(), "no timeout");
    }

    #[test]
    fn test_command_not_found() {
        let output = cmd()
            .args(["10", "nonexistent_cmd_xyz_999"])
            .output()
            .unwrap();
        assert_eq!(output.status.code(), Some(127));
    }
    #[test]
    fn test_missing_operand() {
        let output = cmd().output().unwrap();
        assert_eq!(output.status.code(), Some(125));
    }

    #[test]
    fn test_matches_gnu_exit_codes_success() {
        let gnu = Command::new("timeout")
            .args(["10", "echo", "test"])
            .output();
        if let Ok(gnu) = gnu {
            let ours = cmd().args(["10", "echo", "test"]).output().unwrap();
            assert_eq!(ours.stdout, gnu.stdout, "STDOUT mismatch");
            assert_eq!(ours.status.code(), gnu.status.code(), "Exit code mismatch");
        }
    }

    #[test]
    fn test_matches_gnu_exit_codes_timeout() {
        let gnu = Command::new("timeout")
            .args(["0.1", "sleep", "10"])
            .output();
        if let Ok(gnu) = gnu {
            let ours = cmd().args(["0.1", "sleep", "10"]).output().unwrap();
            assert_eq!(
                ours.status.code(),
                gnu.status.code(),
                "Exit code mismatch on timeout"
            );
        }
    }

    #[test]
    fn test_matches_gnu_exit_codes_not_found() {
        let gnu = Command::new("timeout")
            .args(["10", "nonexistent_cmd_xyz_999"])
            .output();
        if let Ok(gnu) = gnu {
            let ours = cmd()
                .args(["10", "nonexistent_cmd_xyz_999"])
                .output()
                .unwrap();
            assert_eq!(
                ours.status.code(),
                gnu.status.code(),
                "Exit code mismatch for not found"
            );
        }
    }
}