SlideShare a Scribd company logo
1 of 30
Download to read offline
Writing Well-behaved 
Unix Utilities 
Rob Miller • robm.me.uk • @robmil
Who are you? 
• Head of Digital at Big Fish 
• We’re a design, branding and 
marketing consultancy 
• Which is to say:
Who are you? 
• I’ve been programming in Ruby for 
several years now 
• But I don’t do much web development 
any more 
• My world is reporting, sysadmin, ops, 
general tools and utilities 
• Ruby is my tool of choice
The command-line 
spectrum 
• One-liner 
• Script 
• Application
The command-line 
spectrum 
• One-liner 
• Script 
• Application
What makes something 
an “application”? 
• Intended for use by others, or for the 
foreseeable future 
• General-purpose 
• Robust 
• Reusable 
• Built to last
An aside: “Unix” 
• A grouping of computer operating 
systems that behave in a relatively 
standard way 
• In practical terms: 
• Linux (Ubuntu, Debian, Fedora, etc.) 
• Mac OS X 
• BSDs (FreeBSD, OpenBSD, etc.)
The Unix Philosophy 
“…no single program or idea makes 
[Unix] work well. Instead, what makes it 
effective is the approach to 
programming… at its heart is the idea 
that the power of a system comes more 
from the relationships among programs 
than from the programs themselves.
The Unix Philosophy 
“Many UNIX programs do 
quite trivial things in isolation, 
but, combined with other 
programs, become general and 
useful tools.” 
— Brian Kernighan, 1984
The Unix Philosophy 
“This is the Unix philosophy: write 
programs that do one thing and do 
it well. Write programs to work 
together. Write programs to handle 
text streams, because that is a 
universal interface.” 
— Doug McIlroy, c. 1978
The Unix Philosophy 
• To summarise: good Unix applications 
play well with others 
• They respect conventions 
• They’re reusable and general in nature 
• They interact with other processes and 
accept interaction in standard ways 
(files, pipes, sockets)
In Ruby 
• What does this mean in the concrete? 
• How do we write Ruby applications 
that fit this philosophy? 
• Why is Ruby a great choice for writing 
command-line applications?
A good application…
• works with standard input and output 
• works with files 
• communicates via its exit status 
• respects resource limits 
• handles signals 
• accepts command-line options
…works with standard input 
and standard output 
• Pipelines are the foundation of Unix 
• The goal: 
$ grep foo bar | your-app | head 
• Assume that input will come from an 
arbitrary program, and that your 
output will be fed into one too
In Ruby 
$stdin.each do |line| 
puts some_modification(line) 
end 
• Processes input as a stream — handles 
arbitrarily large input (other streaming 
methods work too — each_char, 
read(bytes), etc.) 
• Outputs to $stdout, so can be 
redirected/piped by the user to a file/ 
another process
…works with files too 
• The goal: 
$ cat foo.txt bar.txt | your-app 
$ your-app foo.txt bar.txt 
• The ultimate flexibility. As 
implemented by cat, grep, and most 
other Unix utilities
In Ruby 
ARGF.each do |line| 
# process a line of input 
end 
• No more effort than reading from 
standard input 
• If ARGV is non-empty, its contents will 
be read as files 
• If it is empty, standard input will be 
used instead
…sets an exit status 
• The goal: 
$ your-app 
$ echo $? 
• Was the process successful or not? 
• 0 for success, >0 for failure — so you 
can communicate up to 255 different 
failure states
In Ruby 
if successful? 
exit 
else 
exit 1 
end 
• Use exit to stop execution of your script 
and return a successful exit status 
• Pass it an argument to alter the exit status 
• Document them!
…respects resource limits 
• Processes have resource limits 
• You should respect them, but you 
can also alter them if you need to 
(be reasonable!) 
• Avoid the dreaded Errno::EMFILE: 
Too many open files
In Ruby 
hard, soft = Process.getrlimit(:NOFILE) 
• Check what the limits of your current 
process are (both hard and soft) and take 
appropriate action 
• Here we check EMFILE, the limit of the 
number of file descriptors that we can 
have open at one time
In Ruby 
begin 
File.open(“foo.txt”) 
rescue Errno::EMFILE 
# Do something graceful! 
end 
• Actually handle resource-limit–related 
errors, and do something sensible 
• That might be: increase the limit and try 
the same operation again
In Ruby 
Process.setrlimit(:NOFILE, 4096) 
• Change the soft limit if you need to; you’re 
generally allowed to! 
• Applies to the current process and its 
children, including subshells — so you can 
make sure third-party code behaves too
…handles signals 
• The goal: to be able to communicate with our 
process using signals 
• Common signals: 
• SIGINT: interrupt (Ctrl+C) 
• SIGCHLD: when a child process terminates 
• SIGHUP: when the terminal is closed 
• SIGUSR1, SIGUSR2: custom signals
In Ruby 
trap :INT do 
# close database connection, 
# other necessary cleanup 
exit 
end 
• trap registers a handler for a particular 
signal (in this case SIGINT) 
• When that signal is sent, our block is 
executed
…accepts 
command-line options 
• The goal: 
$ your-app --verbose -o ‘file.txt’ 
• Allow our users to change behaviour 
based on arguments passed 
• Makes our options scriptable — not 
something that has to be chosen from a 
menu or read from a config file
In Ruby 
require “optparse” 
! 
options = { verbose: false } 
OptionParser.new do |opts| 
opts.banner = "Usage: app.rb [options]" 
! 
opts.on("-v", "--verbose") do |v| 
options[:verbose] = true 
end 
end.parse!
In Ruby 
• OptionParser, part of the standard library 
• Gives you: 
• Options, including short aliases 
• Automatic -h help output 
• Removes options from ARGV, so ARGF 
works as you expect 
• No need to use a Gem!
Wrapping Up

More Related Content

What's hot

Writing a fast HTTP parser
Writing a fast HTTP parserWriting a fast HTTP parser
Writing a fast HTTP parserfukamachi
 
Logstash family introduction
Logstash family introductionLogstash family introduction
Logstash family introductionOwen Wu
 
Null Bachaav - May 07 Attack Monitoring workshop.
Null Bachaav - May 07 Attack Monitoring workshop.Null Bachaav - May 07 Attack Monitoring workshop.
Null Bachaav - May 07 Attack Monitoring workshop.Prajal Kulkarni
 
fluent-plugin-beats at Elasticsearch meetup #14
fluent-plugin-beats at Elasticsearch meetup #14fluent-plugin-beats at Elasticsearch meetup #14
fluent-plugin-beats at Elasticsearch meetup #14N Masahiro
 
ApacheCon NA 2011 report
ApacheCon NA 2011 reportApacheCon NA 2011 report
ApacheCon NA 2011 reportKoji Kawamura
 
Pharo Status Fosdem 2015
Pharo Status Fosdem 2015Pharo Status Fosdem 2015
Pharo Status Fosdem 2015Marcus Denker
 
Infrastructure coders logstash
Infrastructure coders logstashInfrastructure coders logstash
Infrastructure coders logstashDavid Lutz
 
20120524 english lt2_pythontoolsfortesting
20120524 english lt2_pythontoolsfortesting20120524 english lt2_pythontoolsfortesting
20120524 english lt2_pythontoolsfortestingKazuhiro Oinuma
 
Woo: Writing a fast web server @ ELS2015
Woo: Writing a fast web server @ ELS2015Woo: Writing a fast web server @ ELS2015
Woo: Writing a fast web server @ ELS2015fukamachi
 
Dexador Rises
Dexador RisesDexador Rises
Dexador Risesfukamachi
 
Ingestion from Kafka Using Gobblin
Ingestion from Kafka Using GobblinIngestion from Kafka Using Gobblin
Ingestion from Kafka Using GobblinZiyang Liu
 
Clack: glue for web apps
Clack: glue for web appsClack: glue for web apps
Clack: glue for web appsfukamachi
 
Continuous Integration for Pharo Smalltalk Part 2 (Smalltalk and Travis CI)
Continuous Integration for Pharo Smalltalk Part 2 (Smalltalk and Travis CI)Continuous Integration for Pharo Smalltalk Part 2 (Smalltalk and Travis CI)
Continuous Integration for Pharo Smalltalk Part 2 (Smalltalk and Travis CI)Sho Yoshida
 
Pharo Status ESUG 2014
Pharo Status ESUG 2014Pharo Status ESUG 2014
Pharo Status ESUG 2014Marcus Denker
 
Sphinx && Perl Houston Perl Mongers - May 8th, 2014
Sphinx && Perl  Houston Perl Mongers - May 8th, 2014Sphinx && Perl  Houston Perl Mongers - May 8th, 2014
Sphinx && Perl Houston Perl Mongers - May 8th, 2014Brett Estrade
 
Woo: Writing a fast web server
Woo: Writing a fast web serverWoo: Writing a fast web server
Woo: Writing a fast web serverfukamachi
 

What's hot (20)

Writing a fast HTTP parser
Writing a fast HTTP parserWriting a fast HTTP parser
Writing a fast HTTP parser
 
Logstash family introduction
Logstash family introductionLogstash family introduction
Logstash family introduction
 
Null Bachaav - May 07 Attack Monitoring workshop.
Null Bachaav - May 07 Attack Monitoring workshop.Null Bachaav - May 07 Attack Monitoring workshop.
Null Bachaav - May 07 Attack Monitoring workshop.
 
DrupalANDElasticsearch
DrupalANDElasticsearchDrupalANDElasticsearch
DrupalANDElasticsearch
 
Kafka Workshop
Kafka WorkshopKafka Workshop
Kafka Workshop
 
Logstash
LogstashLogstash
Logstash
 
fluent-plugin-beats at Elasticsearch meetup #14
fluent-plugin-beats at Elasticsearch meetup #14fluent-plugin-beats at Elasticsearch meetup #14
fluent-plugin-beats at Elasticsearch meetup #14
 
ApacheCon NA 2011 report
ApacheCon NA 2011 reportApacheCon NA 2011 report
ApacheCon NA 2011 report
 
Pharo Status Fosdem 2015
Pharo Status Fosdem 2015Pharo Status Fosdem 2015
Pharo Status Fosdem 2015
 
Infrastructure coders logstash
Infrastructure coders logstashInfrastructure coders logstash
Infrastructure coders logstash
 
Logstash and friends
Logstash and friendsLogstash and friends
Logstash and friends
 
20120524 english lt2_pythontoolsfortesting
20120524 english lt2_pythontoolsfortesting20120524 english lt2_pythontoolsfortesting
20120524 english lt2_pythontoolsfortesting
 
Woo: Writing a fast web server @ ELS2015
Woo: Writing a fast web server @ ELS2015Woo: Writing a fast web server @ ELS2015
Woo: Writing a fast web server @ ELS2015
 
Dexador Rises
Dexador RisesDexador Rises
Dexador Rises
 
Ingestion from Kafka Using Gobblin
Ingestion from Kafka Using GobblinIngestion from Kafka Using Gobblin
Ingestion from Kafka Using Gobblin
 
Clack: glue for web apps
Clack: glue for web appsClack: glue for web apps
Clack: glue for web apps
 
Continuous Integration for Pharo Smalltalk Part 2 (Smalltalk and Travis CI)
Continuous Integration for Pharo Smalltalk Part 2 (Smalltalk and Travis CI)Continuous Integration for Pharo Smalltalk Part 2 (Smalltalk and Travis CI)
Continuous Integration for Pharo Smalltalk Part 2 (Smalltalk and Travis CI)
 
Pharo Status ESUG 2014
Pharo Status ESUG 2014Pharo Status ESUG 2014
Pharo Status ESUG 2014
 
Sphinx && Perl Houston Perl Mongers - May 8th, 2014
Sphinx && Perl  Houston Perl Mongers - May 8th, 2014Sphinx && Perl  Houston Perl Mongers - May 8th, 2014
Sphinx && Perl Houston Perl Mongers - May 8th, 2014
 
Woo: Writing a fast web server
Woo: Writing a fast web serverWoo: Writing a fast web server
Woo: Writing a fast web server
 

Viewers also liked

WordPress and Git
WordPress and GitWordPress and Git
WordPress and GitRob Miller
 
Developing with WordPress and Git
Developing with WordPress and GitDeveloping with WordPress and Git
Developing with WordPress and GitRob Miller
 
Wordpress version control
Wordpress version controlWordpress version control
Wordpress version controlDavid Doolin
 
Migrating a Site Quickly with SSH and WP-CLI (It's not as scary as you think!)
Migrating a Site Quickly with SSH and WP-CLI (It's not as scary as you think!)Migrating a Site Quickly with SSH and WP-CLI (It's not as scary as you think!)
Migrating a Site Quickly with SSH and WP-CLI (It's not as scary as you think!)Japheth Thomson
 
Enhance discovery Solr and Mahout
Enhance discovery Solr and MahoutEnhance discovery Solr and Mahout
Enhance discovery Solr and Mahoutlucenerevolution
 
Introduction to git & WordPress
Introduction to git & WordPressIntroduction to git & WordPress
Introduction to git & WordPressJosh Lee
 
Introducing Git to your FTP workflow
Introducing Git to your FTP workflow Introducing Git to your FTP workflow
Introducing Git to your FTP workflow Roman Rus
 
Some basic unix commands
Some basic unix commandsSome basic unix commands
Some basic unix commandsaaj_sarkar06
 
Linux principles and philosophy
Linux principles and philosophyLinux principles and philosophy
Linux principles and philosophyaliabintouq
 
Unix philosophy and principles
Unix philosophy and principlesUnix philosophy and principles
Unix philosophy and principlesmaryamalmarrii
 
Linux principles and philosophy
Linux principles and philosophyLinux principles and philosophy
Linux principles and philosophyFa6ma_
 
Mobile Knife Fighting at JSConf US
Mobile Knife Fighting at JSConf US Mobile Knife Fighting at JSConf US
Mobile Knife Fighting at JSConf US Brian LeRoux
 
Eduards Sizovs - Micro Service Architecture
Eduards Sizovs - Micro Service Architecture Eduards Sizovs - Micro Service Architecture
Eduards Sizovs - Micro Service Architecture DevConFu
 
Bringing the Unix Philosophy to Big Data
Bringing the Unix Philosophy to Big DataBringing the Unix Philosophy to Big Data
Bringing the Unix Philosophy to Big Databcantrill
 
Mocking Test - QA Ninja Conf 2016
Mocking Test - QA Ninja Conf 2016Mocking Test - QA Ninja Conf 2016
Mocking Test - QA Ninja Conf 2016Renato Groff
 
Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Ve...
Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Ve...Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Ve...
Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Ve...Micha Kops
 
To Microservices and Beyond
To Microservices and BeyondTo Microservices and Beyond
To Microservices and BeyondMatt Stine
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksEndranNL
 
Using Hystrix to Build Resilient Distributed Systems
Using Hystrix to Build Resilient Distributed SystemsUsing Hystrix to Build Resilient Distributed Systems
Using Hystrix to Build Resilient Distributed SystemsMatt Jacobs
 

Viewers also liked (20)

WordPress and Git
WordPress and GitWordPress and Git
WordPress and Git
 
Developing with WordPress and Git
Developing with WordPress and GitDeveloping with WordPress and Git
Developing with WordPress and Git
 
Wordpress version control
Wordpress version controlWordpress version control
Wordpress version control
 
Migrating a Site Quickly with SSH and WP-CLI (It's not as scary as you think!)
Migrating a Site Quickly with SSH and WP-CLI (It's not as scary as you think!)Migrating a Site Quickly with SSH and WP-CLI (It's not as scary as you think!)
Migrating a Site Quickly with SSH and WP-CLI (It's not as scary as you think!)
 
Enhance discovery Solr and Mahout
Enhance discovery Solr and MahoutEnhance discovery Solr and Mahout
Enhance discovery Solr and Mahout
 
Introduction to git & WordPress
Introduction to git & WordPressIntroduction to git & WordPress
Introduction to git & WordPress
 
Introducing Git to your FTP workflow
Introducing Git to your FTP workflow Introducing Git to your FTP workflow
Introducing Git to your FTP workflow
 
Some basic unix commands
Some basic unix commandsSome basic unix commands
Some basic unix commands
 
Linux principles and philosophy
Linux principles and philosophyLinux principles and philosophy
Linux principles and philosophy
 
Unix philosophy and principles
Unix philosophy and principlesUnix philosophy and principles
Unix philosophy and principles
 
Linux principles and philosophy
Linux principles and philosophyLinux principles and philosophy
Linux principles and philosophy
 
Mobile Knife Fighting at JSConf US
Mobile Knife Fighting at JSConf US Mobile Knife Fighting at JSConf US
Mobile Knife Fighting at JSConf US
 
Eduards Sizovs - Micro Service Architecture
Eduards Sizovs - Micro Service Architecture Eduards Sizovs - Micro Service Architecture
Eduards Sizovs - Micro Service Architecture
 
Bringing the Unix Philosophy to Big Data
Bringing the Unix Philosophy to Big DataBringing the Unix Philosophy to Big Data
Bringing the Unix Philosophy to Big Data
 
Mocking Test - QA Ninja Conf 2016
Mocking Test - QA Ninja Conf 2016Mocking Test - QA Ninja Conf 2016
Mocking Test - QA Ninja Conf 2016
 
Unix Philosophy
Unix PhilosophyUnix Philosophy
Unix Philosophy
 
Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Ve...
Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Ve...Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Ve...
Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Ve...
 
To Microservices and Beyond
To Microservices and BeyondTo Microservices and Beyond
To Microservices and Beyond
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworks
 
Using Hystrix to Build Resilient Distributed Systems
Using Hystrix to Build Resilient Distributed SystemsUsing Hystrix to Build Resilient Distributed Systems
Using Hystrix to Build Resilient Distributed Systems
 

Similar to Writing Well-Behaved Unix Utilities

Julia Computing - an alternative to Hadoop
Julia Computing - an alternative to HadoopJulia Computing - an alternative to Hadoop
Julia Computing - an alternative to HadoopShaurya Shekhar
 
Introduction to Python Programming
Introduction to Python ProgrammingIntroduction to Python Programming
Introduction to Python ProgrammingAkhil Kaushik
 
OpenSAF Symposium_Python Bindings_9.21.11
OpenSAF Symposium_Python Bindings_9.21.11OpenSAF Symposium_Python Bindings_9.21.11
OpenSAF Symposium_Python Bindings_9.21.11OpenSAF Foundation
 
Linux operating system by Quontra Solutions
Linux operating system by Quontra SolutionsLinux operating system by Quontra Solutions
Linux operating system by Quontra SolutionsQUONTRASOLUTIONS
 
Algoritmi e Calcolo Parallelo 2012/2013 - OpenMP
Algoritmi e Calcolo Parallelo 2012/2013 - OpenMPAlgoritmi e Calcolo Parallelo 2012/2013 - OpenMP
Algoritmi e Calcolo Parallelo 2012/2013 - OpenMPPier Luca Lanzi
 
How to write a well-behaved Python command line application
How to write a well-behaved Python command line applicationHow to write a well-behaved Python command line application
How to write a well-behaved Python command line applicationgjcross
 
Go: What's Different ?
Go: What's Different ?Go: What's Different ?
Go: What's Different ?Tarun Vashisth
 
Reading Notes : the practice of programming
Reading Notes : the practice of programmingReading Notes : the practice of programming
Reading Notes : the practice of programmingJuggernaut Liu
 
Are High Level Programming Languages for Multicore and Safety Critical Conver...
Are High Level Programming Languages for Multicore and Safety Critical Conver...Are High Level Programming Languages for Multicore and Safety Critical Conver...
Are High Level Programming Languages for Multicore and Safety Critical Conver...InfinIT - Innovationsnetværket for it
 
Repeating History...On Purpose...with Elixir
Repeating History...On Purpose...with ElixirRepeating History...On Purpose...with Elixir
Repeating History...On Purpose...with ElixirBarry Jones
 
computer languages
computer languagescomputer languages
computer languagesRajendran
 
The Ring programming language version 1.6 book - Part 6 of 189
The Ring programming language version 1.6 book - Part 6 of 189The Ring programming language version 1.6 book - Part 6 of 189
The Ring programming language version 1.6 book - Part 6 of 189Mahmoud Samir Fayed
 

Similar to Writing Well-Behaved Unix Utilities (20)

Go fundamentals
Go fundamentalsGo fundamentals
Go fundamentals
 
Cucumber in Practice(en)
Cucumber in Practice(en)Cucumber in Practice(en)
Cucumber in Practice(en)
 
Julia Computing - an alternative to Hadoop
Julia Computing - an alternative to HadoopJulia Computing - an alternative to Hadoop
Julia Computing - an alternative to Hadoop
 
Introduction to multicore .ppt
Introduction to multicore .pptIntroduction to multicore .ppt
Introduction to multicore .ppt
 
sl slides-unit-1.pptx
sl slides-unit-1.pptxsl slides-unit-1.pptx
sl slides-unit-1.pptx
 
Introduction to Python Programming
Introduction to Python ProgrammingIntroduction to Python Programming
Introduction to Python Programming
 
MPI n OpenMP
MPI n OpenMPMPI n OpenMP
MPI n OpenMP
 
OpenSAF Symposium_Python Bindings_9.21.11
OpenSAF Symposium_Python Bindings_9.21.11OpenSAF Symposium_Python Bindings_9.21.11
OpenSAF Symposium_Python Bindings_9.21.11
 
Linux operating system by Quontra Solutions
Linux operating system by Quontra SolutionsLinux operating system by Quontra Solutions
Linux operating system by Quontra Solutions
 
Algoritmi e Calcolo Parallelo 2012/2013 - OpenMP
Algoritmi e Calcolo Parallelo 2012/2013 - OpenMPAlgoritmi e Calcolo Parallelo 2012/2013 - OpenMP
Algoritmi e Calcolo Parallelo 2012/2013 - OpenMP
 
Cucumber presenation
Cucumber presenationCucumber presenation
Cucumber presenation
 
How to write a well-behaved Python command line application
How to write a well-behaved Python command line applicationHow to write a well-behaved Python command line application
How to write a well-behaved Python command line application
 
Plc part 1
Plc part 1Plc part 1
Plc part 1
 
Go: What's Different ?
Go: What's Different ?Go: What's Different ?
Go: What's Different ?
 
Reading Notes : the practice of programming
Reading Notes : the practice of programmingReading Notes : the practice of programming
Reading Notes : the practice of programming
 
Are High Level Programming Languages for Multicore and Safety Critical Conver...
Are High Level Programming Languages for Multicore and Safety Critical Conver...Are High Level Programming Languages for Multicore and Safety Critical Conver...
Are High Level Programming Languages for Multicore and Safety Critical Conver...
 
Repeating History...On Purpose...with Elixir
Repeating History...On Purpose...with ElixirRepeating History...On Purpose...with Elixir
Repeating History...On Purpose...with Elixir
 
computer languages
computer languagescomputer languages
computer languages
 
Class_X_PYTHON_J.pdf
Class_X_PYTHON_J.pdfClass_X_PYTHON_J.pdf
Class_X_PYTHON_J.pdf
 
The Ring programming language version 1.6 book - Part 6 of 189
The Ring programming language version 1.6 book - Part 6 of 189The Ring programming language version 1.6 book - Part 6 of 189
The Ring programming language version 1.6 book - Part 6 of 189
 

Recently uploaded

Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 

Recently uploaded (20)

Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 

Writing Well-Behaved Unix Utilities

  • 1. Writing Well-behaved Unix Utilities Rob Miller • robm.me.uk • @robmil
  • 2. Who are you? • Head of Digital at Big Fish • We’re a design, branding and marketing consultancy • Which is to say:
  • 3. Who are you? • I’ve been programming in Ruby for several years now • But I don’t do much web development any more • My world is reporting, sysadmin, ops, general tools and utilities • Ruby is my tool of choice
  • 4. The command-line spectrum • One-liner • Script • Application
  • 5. The command-line spectrum • One-liner • Script • Application
  • 6. What makes something an “application”? • Intended for use by others, or for the foreseeable future • General-purpose • Robust • Reusable • Built to last
  • 7. An aside: “Unix” • A grouping of computer operating systems that behave in a relatively standard way • In practical terms: • Linux (Ubuntu, Debian, Fedora, etc.) • Mac OS X • BSDs (FreeBSD, OpenBSD, etc.)
  • 8. The Unix Philosophy “…no single program or idea makes [Unix] work well. Instead, what makes it effective is the approach to programming… at its heart is the idea that the power of a system comes more from the relationships among programs than from the programs themselves.
  • 9. The Unix Philosophy “Many UNIX programs do quite trivial things in isolation, but, combined with other programs, become general and useful tools.” — Brian Kernighan, 1984
  • 10. The Unix Philosophy “This is the Unix philosophy: write programs that do one thing and do it well. Write programs to work together. Write programs to handle text streams, because that is a universal interface.” — Doug McIlroy, c. 1978
  • 11. The Unix Philosophy • To summarise: good Unix applications play well with others • They respect conventions • They’re reusable and general in nature • They interact with other processes and accept interaction in standard ways (files, pipes, sockets)
  • 12. In Ruby • What does this mean in the concrete? • How do we write Ruby applications that fit this philosophy? • Why is Ruby a great choice for writing command-line applications?
  • 14. • works with standard input and output • works with files • communicates via its exit status • respects resource limits • handles signals • accepts command-line options
  • 15. …works with standard input and standard output • Pipelines are the foundation of Unix • The goal: $ grep foo bar | your-app | head • Assume that input will come from an arbitrary program, and that your output will be fed into one too
  • 16. In Ruby $stdin.each do |line| puts some_modification(line) end • Processes input as a stream — handles arbitrarily large input (other streaming methods work too — each_char, read(bytes), etc.) • Outputs to $stdout, so can be redirected/piped by the user to a file/ another process
  • 17. …works with files too • The goal: $ cat foo.txt bar.txt | your-app $ your-app foo.txt bar.txt • The ultimate flexibility. As implemented by cat, grep, and most other Unix utilities
  • 18. In Ruby ARGF.each do |line| # process a line of input end • No more effort than reading from standard input • If ARGV is non-empty, its contents will be read as files • If it is empty, standard input will be used instead
  • 19. …sets an exit status • The goal: $ your-app $ echo $? • Was the process successful or not? • 0 for success, >0 for failure — so you can communicate up to 255 different failure states
  • 20. In Ruby if successful? exit else exit 1 end • Use exit to stop execution of your script and return a successful exit status • Pass it an argument to alter the exit status • Document them!
  • 21. …respects resource limits • Processes have resource limits • You should respect them, but you can also alter them if you need to (be reasonable!) • Avoid the dreaded Errno::EMFILE: Too many open files
  • 22. In Ruby hard, soft = Process.getrlimit(:NOFILE) • Check what the limits of your current process are (both hard and soft) and take appropriate action • Here we check EMFILE, the limit of the number of file descriptors that we can have open at one time
  • 23. In Ruby begin File.open(“foo.txt”) rescue Errno::EMFILE # Do something graceful! end • Actually handle resource-limit–related errors, and do something sensible • That might be: increase the limit and try the same operation again
  • 24. In Ruby Process.setrlimit(:NOFILE, 4096) • Change the soft limit if you need to; you’re generally allowed to! • Applies to the current process and its children, including subshells — so you can make sure third-party code behaves too
  • 25. …handles signals • The goal: to be able to communicate with our process using signals • Common signals: • SIGINT: interrupt (Ctrl+C) • SIGCHLD: when a child process terminates • SIGHUP: when the terminal is closed • SIGUSR1, SIGUSR2: custom signals
  • 26. In Ruby trap :INT do # close database connection, # other necessary cleanup exit end • trap registers a handler for a particular signal (in this case SIGINT) • When that signal is sent, our block is executed
  • 27. …accepts command-line options • The goal: $ your-app --verbose -o ‘file.txt’ • Allow our users to change behaviour based on arguments passed • Makes our options scriptable — not something that has to be chosen from a menu or read from a config file
  • 28. In Ruby require “optparse” ! options = { verbose: false } OptionParser.new do |opts| opts.banner = "Usage: app.rb [options]" ! opts.on("-v", "--verbose") do |v| options[:verbose] = true end end.parse!
  • 29. In Ruby • OptionParser, part of the standard library • Gives you: • Options, including short aliases • Automatic -h help output • Removes options from ARGV, so ARGF works as you expect • No need to use a Gem!