Complex Stream Handling
Advanced Stream Manipulation Techniques
Simultaneous Stream Processing
graph LR
A[Input Stream] --> B{Stream Processor}
B -->|stdout| C[Output Stream]
B -->|stderr| D[Error Log]
Parallel Stream Execution
## Parallel command execution with stream management
(
{ find / -name "*.log" 2> /dev/null; } &
{ du -sh /home/* 2> /dev/null; } &
wait
) | tee system_analysis.txt
Stream Redirection Patterns
Conditional Stream Handling
Scenario |
Redirection Strategy |
Error Logging |
Separate error streams |
Silent Execution |
Redirect to /dev/null |
Debugging |
Capture all streams |
Complex Redirection Example
## Advanced stream management script
process_data() {
local input_file=$1
local output_file=$2
## Redirect multiple streams
{
echo "Processing started..."
grep "critical" "$input_file" || true
sort "$input_file"
} 1> "$output_file" 2> error_log.txt
}
Stream Manipulation with awk
and sed
## Real-time log processing
tail -f /var/log/syslog \
| awk '/error/ {print strftime("%Y-%m-%d %H:%M:%S"), $0}' \
| tee -a filtered_logs.txt
Asynchronous Stream Handling
Background Process Stream Management
## Non-blocking stream processing
(
long_running_command > output.log 2> error.log &
background_pid=$!
## Monitor background process
wait $background_pid
)
Advanced Techniques
Named Pipes (FIFOs)
## Create named pipe for inter-process communication
mkfifo /tmp/data_pipe
## Producer process
echo "Data transmission" > /tmp/data_pipe &
## Consumer process
cat /tmp/data_pipe
Stream Buffering Strategies
## Unbuffered stream processing
python3 -u script.py \
| while read line; do
echo "Processed: $line"
done
Error Handling and Logging
Comprehensive Error Capture
## Robust error handling
{
command_that_might_fail || {
echo "Command failed with status $?"
exit 1
}
} 2> >(tee -a error_log.txt >&2)
- Minimize unnecessary stream operations
- Use efficient stream processing tools
- Implement proper error handling
- Consider memory and CPU usage
LabEx Recommended Practices
- Use stream redirection judiciously
- Always validate input and output streams
- Implement robust error handling mechanisms
By mastering these complex stream handling techniques, you'll develop more sophisticated and reliable Linux applications with advanced input/output management capabilities.