SlideShare ist ein Scribd-Unternehmen logo
1 von 30
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durbanmasabamasaba
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsBert Jan Schrijver
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 

Kürzlich hochgeladen (20)

10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 

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!