SlideShare a Scribd company logo
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 parser
fukamachi
 
Logstash family introduction
Logstash family introductionLogstash family introduction
Logstash family introduction
Owen 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
 
Kafka Workshop
Kafka WorkshopKafka Workshop
Kafka Workshop
Alexandre André
 
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
N 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 2015
Marcus Denker
 
Infrastructure coders logstash
Infrastructure coders logstashInfrastructure coders logstash
Infrastructure coders logstash
David Lutz
 
Logstash and friends
Logstash and friendsLogstash and friends
Logstash and friends
Julien Pivotto
 
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 @ ELS2015
fukamachi
 
Dexador Rises
Dexador RisesDexador Rises
Dexador Rises
fukamachi
 
Ingestion from Kafka Using Gobblin
Ingestion from Kafka Using GobblinIngestion from Kafka Using Gobblin
Ingestion from Kafka Using Gobblin
Ziyang Liu
 
Clack: glue for web apps
Clack: glue for web appsClack: glue for web apps
Clack: glue for web apps
fukamachi
 
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 2014
Marcus 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, 2014
Brett Estrade
 
Woo: Writing a fast web server
Woo: Writing a fast web serverWoo: Writing a fast web server
Woo: Writing a fast web server
fukamachi
 

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 Git
Rob Miller
 
Developing with WordPress and Git
Developing with WordPress and GitDeveloping with WordPress and Git
Developing with WordPress and Git
Rob 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 Mahout
lucenerevolution
 
Introduction to git & WordPress
Introduction to git & WordPressIntroduction to git & WordPress
Introduction to git & WordPress
Josh 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 philosophy
aliabintouq
 
Unix philosophy and principles
Unix philosophy and principlesUnix philosophy and principles
Unix philosophy and principles
maryamalmarrii
 
Linux principles and philosophy
Linux principles and philosophyLinux principles and philosophy
Linux principles and philosophy
Fa6ma_
 
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 Data
bcantrill
 
Mocking Test - QA Ninja Conf 2016
Mocking Test - QA Ninja Conf 2016Mocking Test - QA Ninja Conf 2016
Mocking Test - QA Ninja Conf 2016
Renato 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 Beyond
Matt 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 frameworks
EndranNL
 
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
Matt 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

Go fundamentals
Go fundamentalsGo fundamentals
Go fundamentals
Ron Barabash
 
Cucumber in Practice(en)
Cucumber in Practice(en)Cucumber in Practice(en)
Cucumber in Practice(en)
Kyosuke MOROHASHI
 
Julia Computing - an alternative to Hadoop
Julia Computing - an alternative to HadoopJulia Computing - an alternative to Hadoop
Julia Computing - an alternative to Hadoop
Shaurya Shekhar
 
sl slides-unit-1.pptx
sl slides-unit-1.pptxsl slides-unit-1.pptx
sl slides-unit-1.pptx
SRAVANTHISALLARAM1
 
Introduction to Python Programming
Introduction to Python ProgrammingIntroduction to Python Programming
Introduction to Python Programming
Akhil 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.11
OpenSAF 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 - OpenMP
Pier 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 application
gjcross
 
Plc part 1
Plc part 1Plc part 1
Plc part 1
Taymoor Nazmy
 
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 programming
Juggernaut 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 Elixir
Barry Jones
 
computer languages
computer languagescomputer languages
computer languages
Rajendran
 
Class_X_PYTHON_J.pdf
Class_X_PYTHON_J.pdfClass_X_PYTHON_J.pdf
Class_X_PYTHON_J.pdf
SanjeedaPraween
 
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
Mahmoud 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

Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 

Recently uploaded (20)

Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 

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!