set this_image to open "$OUTFILE"
scale this_image by factor $NEWSCALE
save this_image with icon
copy dimensions of this_image to {W, H}
close this_image
end tell
return W & H
EOF
)"
GOTW="$(echo "$DIM" | sed 's/ *, *.*//' )"
GOTH="$(echo "$DIM" | sed 's/.* *, *//' )"
echo "NEW WIDTH: $GOTW NEW HEIGHT: $GOTH"
Ofcourse,youcouldjustaseasilyperformthesecalculationsinAppleScriptitself,butthisdemonstrateshow
easyitisforshellscriptstoexchangeinformationwithAppleScriptcode,manipulateimagefiles,andtell
applicationstoperformothercomplextasks.
FormoreinformationaboutmanipulatingimageswithImageEvents,seehttp://www.apple.com/applescript/im-
ageevents/.YoucanalsofindmanyotherAppleScriptexamplesat http://www.apple.com/applescript/exam-
ples.html.
Scripting InteractiveTools Using FileDescriptors
Mostofthetime,youshoulduse
expect
scriptsorCprogramstocontrolinteractivetools.However,itis
sometimespossible,albeitsometimesdifficult,toscriptsuchinteractivetools(iftheiroutputisline-based).
Thissectionexplainsthetechniquesyouuse.
AdvancedTechniques
ScriptingInteractiveToolsUsingFileDescriptors
2014-03-10   |   Copyright © 2003, 2014 Apple Inc. All Rights Reserved.
211
Pdf extract pages - SDK control project:C# PDF Page Extract Library: copy, paste, cut PDF pages in C#.net, ASP.NET, MVC, Ajax, WinForms, WPF
Easy to Use C# Code to Extract PDF Pages, Copy Pages from One PDF File and Paste into Others
www.rasteredge.com
Pdf extract pages - SDK control project:VB.NET PDF Page Extract Library: copy, paste, cut PDF pages in vb.net, ASP.NET, MVC, Ajax, WinForms, WPF
Detailed VB.NET Guide for Extracting Pages from Microsoft PDF Doc
www.rasteredge.com
C Shell Note:  ThelackoffiledescriptorredirectionisoneofthemoreseriousflawsintheCshell.
ThetechniquesdescribedinthissectionarenotpossibleinCshelloritsvariants.
CreatingNamedPipes
Beforeyoucancommunicatewithatoolinacontinuousround-tripfashion,youmustcreateapairofFIFOs
(shortforfirst-in,first-out,otherwiseknownasnamedpipes)usingthe
mkfifo
command.Forexample,to
createnamedpipescalled
/tmp/infifo
and
/tmp/outfifo
,youwouldissuethefollowingcommands:
mkfifo /tmp/infifo
mkfifo /tmp/outfifo
Toseethisinactionusingthe
sed
commandasafilter,typethefollowingcommands:
mkfifo /tmp/outfifo
sed 's/a/b/' < /tmp/outfifo &
echo "This is a test" > /tmp/outfifo
Noticethat
sed
exitsafterreceivingthedataandprinting
This is b test
tothescreen.The
echo
command
openstheoutputFIFO,writesthedata,andclosestheFIFO.AssoonasitclosestheFIFO,the
sed
command
getsa
SIGPIPE
signaland(usually)terminates.Touseacommand-linetoolasafilterandkeeppassingdata
toit,youmustmakesurethatyoudon'tclosetheFIFOuntilyouarefinishedusingthefilter.Toachievethis,
youmustusefiledescriptors,asdescribedinthenextsection.
OpeningFileDescriptorsforReadingandWriting
AsexplainedinCreatingNamedPipes (page 212),sendingdatatoanamedpipewithcommand-linetools
causesthecommandtoterminateafterthefirstmessage.Topreventthis,youmustopenafiledescriptorin
theshelltoprovidecontinuousaccesstothenamedpipe.
YoucanopenafiledescriptorforwritingtotheoutputFIFOasfollows:
exec 8> /tmp/outfifo
Thiscommandopensfiledescriptor8andredirectsittothefile/tmp/outfifo.
AdvancedTechniques
ScriptingInteractiveToolsUsingFileDescriptors
2014-03-10   |   Copyright © 2003, 2014 Apple Inc. All Rights Reserved.
212
SDK control project:C# PDF Text Extract Library: extract text content from PDF file in
inputFilePath); PDFTextMgr textMgr = PDFTextHandler.ExportPDFTextManager(doc); // Extract text content C# example code for text extraction from all PDF pages.
www.rasteredge.com
SDK control project:VB.NET PDF Text Extract Library: extract text content from PDF
PDF ›› VB.NET PDF: Extract PDF Text. VB.NET PDF - Extract Text from PDF Using VB. How to Extract Text from PDF with VB.NET Sample Codes in .NET Application.
www.rasteredge.com
Note:  Youmustchooseafiledescriptornumberthatisunused.Typicallyyourscripthasthreefile
descriptorsopeninitially—descriptor
0
(standardinput),descriptor
1
(standardoutput),anddescriptor
2
(standarderror).Justtobesafe,thisexampleusesdescriptor
8
.
Similarly,youcanopenadescriptorforreadinglikethis:
exec 9<> /tmp/infifo
Youcanwritedatatoanopendescriptorlikethis:
# Write a string to descriptor 8
echo "This is a test." >&8
Youcanreadalinefromanopendescriptorlikethis:
# Read a line from descriptor 9 and store the result in variable MYLINE
read MYLINE <&9
Whenyouhavefinishedwritingdatatothefilter,youshouldclosethepipesanddeletetheFIFOfilesasfollows:
exec 8>&-
exec 9<&-
rm /tmp/infifo
rm /tmp/outfifo
Table11-5 (page 213)summarizestheoperationsyoucanperformonfiledescriptors.Thenextsectioncontains
acompleteworkingexample.
Table11-5
Shellfiledescriptoroperators
EquivalentCcode
Operator
fd = open("
filename
", O_RDWR|O_CREAT);
dup2(fd,
n)
;
close(fd);
n
<> "filename"
AdvancedTechniques
ScriptingInteractiveToolsUsingFileDescriptors
2014-03-10   |   Copyright © 2003, 2014 Apple Inc. All Rights Reserved.
213
SDK control project:C# PDF Image Extract Library: Select, copy, paste PDF images in C#
Image: Extract Image from PDF. |. Home ›› XDoc.PDF ›› C# PDF: Extract PDF Image. How to C#: Extract Image from PDF Document.
www.rasteredge.com
SDK control project:VB.NET PDF Image Extract Library: Select, copy, paste PDF images
Image: Extract Image from PDF. |. Home ›› XDoc.PDF ›› VB.NET PDF: Extract PDF Image. VB.NET PDF - Extract Image from PDF Document in VB.NET.
www.rasteredge.com
EquivalentCcode
Operator
fd = open("
filename
", O_WRONLY|O_CREAT|O_TRUNC);
dup2(fd,
n)
;
close(fd);
n
> "filename"
fd = open("
filename
", O_WRONLY|O_APPEND|O_CREAT);
dup2(fd,
n)
;
close(fd);
n
>> "filename"
dup2(
o
,
n)
;
Note:Althoughtheseoperatorsbehaveidentically,forreadability,youshould
usethe
<&
operatorforread-onlyorread-writedescriptorsandthe
>&
for
write-onlydescriptors.
n
<&
o
n
>&
o
close(
n
);
n
<&-
n
<&-
UsingNamedPipesandFileDescriptorstoCreateCircularPipes
There’sjustonemoreproblem.The
sed
commandbuffersitsinputbydefault.Thiscancauseproblemswhen
usingitasafilter.Thus,youmusttellthe
sed
commandtonotbufferitsinputbyspecifyingthe
-l
flag(or
the
-u
flagforGNU
sed
).
Thefollowinglistingdemonstratesthesetechniques.Itruns
sed
,thensendstwostringstoit,thenreadsback
thetwofilteredstrings,thensendsathirdstring,thenreadsthethirdfilteredstringback,thenclosesthepipes.
Listing
11-14
UsingFIFOstocreatecircularpipes
#!/bin/sh
# Create two FIFOs (named pipes)
INFIFO="/tmp/infifo.$$"
OUTFIFO="/tmp/outfifo.$$"
mkfifo "$INFIFO"
mkfifo "$OUTFIFO"
# OS X and recent *BSD sed uses -l for line-buffered mode.
AdvancedTechniques
ScriptingInteractiveToolsUsingFileDescriptors
2014-03-10   |   Copyright © 2003, 2014 Apple Inc. All Rights Reserved.
214
SDK control project:C# PDF Page Insert Library: insert pages into PDF file in C#.net
Page: Insert PDF Pages. |. Home ›› XDoc.PDF ›› C# PDF: Insert PDF Page. Add and Insert Multiple PDF Pages to PDF Document Using C#.
www.rasteredge.com
SDK control project:VB.NET PDF Page Delete Library: remove PDF pages in vb.net, ASP.
Page: Delete Existing PDF Pages. |. Home ›› XDoc.PDF ›› VB.NET PDF: Delete PDF Page. How to VB.NET: Delete Consecutive Pages from PDF.
www.rasteredge.com
BUFFER_FLAG="-l"
# GNU sed uses -u for "unbuffered" mode (really line-buffered).
if [ "x$(sed --version 2>&1 | grep GNU)" != "x" ] ; then
BUFFER_FLAG="-u"
fi
# Set up a sed substitution input from the input fifo otput to
sed $BUFFER_FLAG 's/a test/not a test/' < $INFIFO > $OUTFIFO &
PID=$!
# Open a file descriptor (#8) to write to the input FIFO
exec 8> $INFIFO
# Open a file descriptor (#9) to read from the output FIFO.
exec 9<> $OUTFIFO
# Send two lines of text to the running copy of sed.
echo "This is a test." >&8
echo "This is maybe a test." >&8
# Read the first two lines from sed's output.
read A <&9
echo "Result 1: $A"
read A <&9
echo "Result 2: $A"
# Send another line of text to the running copy of sed.
echo "This is also a test." >&8
# Read it back.
read A <&9
echo "Result 3: $A"
# Show that sed is still running.
AdvancedTechniques
ScriptingInteractiveToolsUsingFileDescriptors
2014-03-10   |   Copyright © 2003, 2014 Apple Inc. All Rights Reserved.
215
SDK control project:C# PDF Page Delete Library: remove PDF pages in C#.net, ASP.NET
Page: Delete Existing PDF Pages. Provide C# Users with Mature .NET PDF Document Manipulating Library for Deleting PDF Pages in C#.
www.rasteredge.com
SDK control project:VB.NET PDF Page Insert Library: insert pages into PDF file in vb.
Page: Insert PDF Pages. |. Home ›› XDoc.PDF ›› VB.NET PDF: Insert PDF Page. Add and Insert Multiple PDF Pages to PDF Document Using VB.
www.rasteredge.com
ps -p $PID
# Close the pipes to terminate sed.
exec 8>&-
exec 9<&-
# Show that sed is no longer running.
ps -p $PID
# Clean up the FIFO files in /tmp
rm "$INFIFO"
rm "$OUTFIFO"
Networking With Shell Scripts
BybuildingontheconceptsinUsingNamedPipesandFileDescriptorstoCreateCircularPipes (page 214),you
caneasilywritescriptsthatcommunicateovertheInternetusingTCP/IPusingthenetcatutility,
nc
.Thisutility
iscommonlyavailableinvariousformsondifferentplatforms,andtheavailableflagsvarysomewhatfrom
platformtoplatform.
Thefollowinglistingshowshowtowriteaverysimpledaemonbasedonnetcatthatworksportably.Itlistens
onport4242.Whenaclientconnects,itreadsalineoftext,thensendstheclientthesameline,onlybackwards.
Itrepeatsthisprocessuntiltheclientclosestheconnection.
Listing
11-15
Asimpledaemonbasedonnetcat
#!/bin/sh
INFIFO="/tmp/infifo.$$"
OUTFIFO="/tmp/outfifo.$$"
# /*! Cleans up the FIFOs and kills the netcat helper. */
cleanup_daemon()
{
AdvancedTechniques
NetworkingWithShellScripts
2014-03-10   |   Copyright © 2003, 2014 Apple Inc. All Rights Reserved.
216
rm -f "$INFIFO" "$OUTFIFO"
if [ "$NCPID" != "" ] ; then
kill -TERM "$NCPID"
fi
exit
}
# /*! @abstract Attempts to reconnect after a sigpipe. */
reconnect()
{
PSOUT="$(ps -p $NCPID | tail -n +2 | tr -d '\n')"
if [ "$PSOUT" = "" ] ; then
cleanup_shttpd
fi
closeConnection 8 "$INFIFO"
}
trap cleanup_daemon SIGHUP
trap cleanup_daemon SIGTERM
trap reconnect SIGPIPE
trap cleanup_daemon SIGABRT
trap cleanup_daemon SIGTSTP
# trap cleanup_daemon SIGCHLD
trap cleanup_daemon SIGSEGV
trap cleanup_daemon SIGBUS
trap cleanup_daemon SIGQUIT
trap cleanup_daemon SIGINT
mkfifo "$INFIFO"
mkfifo "$OUTFIFO"
# /*! Reverses a string. */
reverseit()
AdvancedTechniques
NetworkingWithShellScripts
2014-03-10   |   Copyright © 2003, 2014 Apple Inc. All Rights Reserved.
217
{
STRING="$1"
REPLY=""
while [ "$STRING" != "" ] ; do
FIRST="$(echo "$STRING" | cut -c '1')"
STRING="$(echo "$STRING" | cut -c '2-')"
REPLY="$FIRST$REPLY"
done
echo "$REPLY"
}
while true ; do
CONNECTED=1
nc -l 4242 < $INFIFO > $OUTFIFO &
NCPID=$!
exec 8> $INFIFO
exec 9<> $OUTFIFO
while [ $CONNECTED = 1 ]
; do
read -u9 -t1 REQUEST
if [ $? = 0 ] ; then
# Read didn't time out.
reverseit "$REQUEST" >&8
echo "GOT REQUEST $REQUEST"
fi
CONNECTED="$(jobs -r | grep -c .)"
done
done
AdvancedTechniques
NetworkingWithShellScripts
2014-03-10   |   Copyright © 2003, 2014 Apple Inc. All Rights Reserved.
218
Thisdaemonisdesignedtobeportable,whichlimitstheflagsitcanuse.Asaresult,itcanonlyhandleasingle
clientatanygiventime,withaminimumofaonesecondperiodbetweenconnectionattempts.Thisisthe
easiestwaytousethenetcatutility.Foramorecomplexexample,seeAShell-BasedWebServer (page 284).
Youcanalsousenetcatasanetworkingclientinmuchthesameway.Youmightsendarequesttoaweb
server,amailserver,orotherdaemon.Ofcourse,youaregenerallybetteroffusingexistingclientssuchas
curl
or
sendmail
,butwhenthatisnotpossible,netcatprovidesasolution.
ThefollowinglistingconnectstothedaemonshowninListing11-15 (page 216),requestsinputfromtheuser,
sendstheinputtotheremotedaemon,readstheresult,andprintsittostandardoutput.
Listing
11-16
Asimpleclientbasedonnetcat
#!/bin/sh
INFIFO="/tmp/infifo.$$"
OUTFIFO="/tmp/outfifo.$$"
INFIFO="/tmp/infifo.$$"
OUTFIFO="/tmp/outfifo.$$"
# /*! Cleans up the FIFOs and kills the netcat helper. */
cleanup_client()
{
rm -f "$INFIFO" "$OUTFIFO"
if [ "$NCPID" != "" ] ; then
kill -TERM "$NCPID"
fi
exit
}
# /*! @abstract Attempts to reconnect after a sigpipe. */
reconnect()
AdvancedTechniques
NetworkingWithShellScripts
2014-03-10   |   Copyright © 2003, 2014 Apple Inc. All Rights Reserved.
219
{
PSOUT="$(ps -p $NCPID | tail -n +2 | tr -d '\n')"
if [ "$PSOUT" = "" ] ; then
cleanup_shttpd
fi
closeConnection 8 "$INFIFO"
}
trap cleanup_client SIGHUP
trap cleanup_client SIGTERM
trap reconnect SIGPIPE
trap cleanup_client SIGABRT
trap cleanup_client SIGTSTP
trap cleanup_client SIGCHLD
trap cleanup_client SIGSEGV
trap cleanup_client SIGBUS
trap cleanup_client SIGQUIT
trap cleanup_client SIGINT
mkfifo "$INFIFO"
mkfifo "$OUTFIFO"
nc localhost 4242 < $INFIFO > $OUTFIFO &
NCPID=$!
exec 8> $INFIFO
exec 9<> $OUTFIFO
while true ; do
printf "String to reverse -> "
read STRING
echo "$STRING" >&8
read -u9 REVERSED
echo "$REVERSED"
AdvancedTechniques
NetworkingWithShellScripts
2014-03-10   |   Copyright © 2003, 2014 Apple Inc. All Rights Reserved.
220
Documents you may be interested
Documents you may be interested