|
| 1 | +use std::fs::OpenOptions; |
| 2 | +use std::os::fd::AsRawFd; |
| 3 | +use std::path::Path; |
| 4 | + |
| 5 | +use a653rs::partition; |
| 6 | +use a653rs::prelude::PartitionExt; |
| 7 | +use a653rs_linux::partition::ApexLogger; |
| 8 | +use anyhow::Result; |
| 9 | +use log::LevelFilter; |
| 10 | + |
| 11 | +fn replace_stdio<T: AsRawFd, U: AsRef<Path>>(stdio: T, new: U, write: bool) -> Result<()> { |
| 12 | + let new = OpenOptions::new() |
| 13 | + .write(write) |
| 14 | + .read(!write) |
| 15 | + .truncate(write) |
| 16 | + .open(new)?; |
| 17 | + nix::unistd::dup2(new.as_raw_fd(), stdio.as_raw_fd())?; |
| 18 | + Ok(()) |
| 19 | +} |
| 20 | + |
| 21 | +fn main() { |
| 22 | + replace_stdio(std::io::stdin(), "/stdin", false).unwrap(); |
| 23 | + replace_stdio(std::io::stdout(), "/stdout", true).unwrap(); |
| 24 | + replace_stdio(std::io::stderr(), "/stderr", true).unwrap(); |
| 25 | + |
| 26 | + ApexLogger::install_panic_hook(); |
| 27 | + ApexLogger::install_logger(LevelFilter::Trace).unwrap(); |
| 28 | + |
| 29 | + redirect_stdio::Partition.run() |
| 30 | +} |
| 31 | + |
| 32 | +#[partition(a653rs_linux::partition::ApexLinuxPartition)] |
| 33 | +mod redirect_stdio { |
| 34 | + use log::info; |
| 35 | + use std::io::BufRead; |
| 36 | + |
| 37 | + #[start(cold)] |
| 38 | + fn cold_start(mut ctx: start::Context) { |
| 39 | + // create and start an aperiodic process |
| 40 | + ctx.create_process_0().unwrap().start().unwrap(); |
| 41 | + } |
| 42 | + |
| 43 | + // do the same as a cold_start |
| 44 | + #[start(warm)] |
| 45 | + fn warm_start(ctx: start::Context) { |
| 46 | + cold_start(ctx); |
| 47 | + } |
| 48 | + |
| 49 | + // this aperiodic process opens /dev/random and reads some random bytes from it |
| 50 | + #[aperiodic( |
| 51 | + time_capacity = "Infinite", |
| 52 | + stack_size = "8KB", |
| 53 | + base_priority = 1, |
| 54 | + deadline = "Soft" |
| 55 | + )] |
| 56 | + fn process_0(ctx: process_0::Context) { |
| 57 | + info!("started process with redirected stdio/stdout/stderr"); |
| 58 | + |
| 59 | + info!("Reading stdin to stdout"); |
| 60 | + println!("Start reading stdin to stdout"); |
| 61 | + let stdin = std::io::stdin(); |
| 62 | + for line in stdin.lock().lines() { |
| 63 | + println!("{}", line.unwrap()) |
| 64 | + } |
| 65 | + println!("Finished reading stdin to stdout"); |
| 66 | + |
| 67 | + info!("Writing messages to stderr"); |
| 68 | + eprintln!("Error was encountered: None"); |
| 69 | + eprintln!("But it was printed to stderr"); |
| 70 | + |
| 71 | + info!("Terminating partition"); |
| 72 | + ctx.set_partition_mode(OperatingMode::Idle).unwrap(); |
| 73 | + } |
| 74 | +} |
0 commit comments