home *** CD-ROM | disk | FTP | other *** search
/ ftp.pasteur.org/FAQ/ / ftp-pasteur-org-FAQ.zip / FAQ / unix-faq / faq / part3 < prev    next >
Encoding:
Internet Message Format  |  2004-05-12  |  45.0 KB

  1. Path: senator-bedfellow.mit.edu!dreaderd!not-for-mail
  2. Message-ID: <unix-faq/faq/part3_1084272547@rtfm.mit.edu>
  3. Supersedes: <unix-faq/faq/part3_1083581613@rtfm.mit.edu>
  4. Expires: 8 Jun 2004 10:49:07 GMT
  5. References: <unix-faq/faq/contents_1084272547@rtfm.mit.edu>
  6. X-Last-Updated: 1996/06/11
  7. From: tmatimar@isgtec.com (Ted Timar)
  8. Distribution: world
  9. Newsgroups: comp.unix.questions,comp.unix.shell,comp.answers,news.answers
  10. Followup-To: comp.unix.questions
  11. Organization: ISG Technologies, Inc
  12. Subject: Unix - Frequently Asked Questions (3/7) [Frequent posting]
  13. Approved: news-answers-request@MIT.Edu
  14. Originator: faqserv@penguin-lust.MIT.EDU
  15. Date: 11 May 2004 10:50:00 GMT
  16. Lines: 1091
  17. NNTP-Posting-Host: penguin-lust.mit.edu
  18. X-Trace: 1084272600 senator-bedfellow.mit.edu 576 18.181.0.29
  19. Xref: senator-bedfellow.mit.edu comp.unix.questions:195436 comp.unix.shell:165513 comp.answers:57116 news.answers:271072
  20.  
  21. Archive-name: unix-faq/faq/part3
  22. Version: $Id: part3,v 2.9 1996/06/11 13:07:56 tmatimar Exp $
  23.  
  24. These seven articles contain the answers to some Frequently Asked
  25. Questions often seen in comp.unix.questions and comp.unix.shell.
  26. Please don't ask these questions again, they've been answered plenty
  27. of times already - and please don't flame someone just because they may
  28. not have read this particular posting.  Thank you.
  29.  
  30. This collection of documents is Copyright (c) 1994, Ted Timar, except
  31. Part 6, which is Copyright (c) 1994, Pierre Lewis and Ted Timar.
  32. All rights reserved.  Permission to distribute the collection is
  33. hereby granted providing that distribution is electronic, no money
  34. is involved, reasonable attempts are made to use the latest version
  35. and all credits and this copyright notice are maintained.
  36. Other requests for distribution will be considered.  All reasonable
  37. requests will be granted.
  38.  
  39. All information here has been contributed with good intentions, but
  40. none of it is guaranteed either by the contributors or myself to be
  41. accurate.  The users of this information take all responsibility for
  42. any damage that may occur.
  43.  
  44. Many FAQs, including this one, are available on the archive site
  45. rtfm.mit.edu in the directory pub/usenet/news.answers.
  46. The name under which a FAQ is archived appears in the "Archive-Name:"
  47. line at the top of the article.  This FAQ is archived as
  48. "unix-faq/faq/part[1-7]".
  49.  
  50. These articles are divided approximately as follows:
  51.  
  52.       1.*) General questions.
  53.       2.*) Relatively basic questions, likely to be asked by beginners.
  54.       3.*) Intermediate questions.
  55.       4.*) Advanced questions, likely to be asked by people who thought
  56.            they already knew all of the answers.
  57.       5.*) Questions pertaining to the various shells, and the differences.
  58.       6.*) An overview of Unix variants.
  59.       7.*) An comparison of configuration management systems (RCS, SCCS).
  60.  
  61. This article includes answers to:
  62.  
  63.       3.1)  How do I find the creation time of a file?
  64.       3.2)  How do I use "rsh" without having the rsh hang around
  65.               until the remote command has completed?
  66.       3.3)  How do I truncate a file?
  67.       3.4)  Why doesn't find's "{}" symbol do what I want?
  68.       3.5)  How do I set the permissions on a symbolic link?
  69.       3.6)  How do I "undelete" a file?
  70.       3.7)  How can a process detect if it's running in the background?
  71.       3.8)  Why doesn't redirecting a loop work as intended?  (Bourne shell)
  72.       3.9)  How do I run 'passwd', 'ftp', 'telnet', 'tip' and other interactive
  73.               programs from a shell script or in the background?
  74.       3.10) How do I find the process ID of a program with a particular
  75.             name from inside a shell script or C program?
  76.       3.11) How do I check the exit status of a remote command
  77.             executed via "rsh" ?
  78.       3.12) Is it possible to pass shell variable settings into an awk program?
  79.       3.13) How do I get rid of zombie processes that persevere?
  80.       3.14) How do I get lines from a pipe as they are written instead of
  81.             only in larger blocks?
  82.       3.15) How do I get the date into a filename?
  83.       3.16) Why do some scripts start with #! ... ?
  84.  
  85. If you're looking for the answer to, say, question 3.5, and want to skip
  86. everything else, you can search ahead for the regular expression "^3.5)".
  87.  
  88. While these are all legitimate questions, they seem to crop up in
  89. comp.unix.questions or comp.unix.shell on an annual basis, usually
  90. followed by plenty of replies (only some of which are correct) and then
  91. a period of griping about how the same questions keep coming up.  You
  92. may also like to read the monthly article "Answers to Frequently Asked
  93. Questions" in the newsgroup "news.announce.newusers", which will tell
  94. you what "UNIX" stands for.
  95.  
  96. With the variety of Unix systems in the world, it's hard to guarantee
  97. that these answers will work everywhere.  Read your local manual pages
  98. before trying anything suggested here.  If you have suggestions or
  99. corrections for any of these answers, please send them to to
  100. tmatimar@isgtec.com.
  101.  
  102. ----------------------------------------------------------------------
  103.  
  104. Subject: How do I find the creation time of a file?
  105. Date: Thu Mar 18 17:16:55 EST 1993
  106.  
  107. 3.1)  How do I find the creation time of a file?
  108.  
  109.       You can't - it isn't stored anywhere.  Files have a last-modified
  110.       time (shown by "ls -l"), a last-accessed time (shown by "ls -lu")
  111.       and an inode change time (shown by "ls -lc"). The latter is often
  112.       referred to as the "creation time" - even in some man pages -
  113.       but that's wrong; it's also set by such operations as mv, ln,
  114.       chmod, chown and chgrp.
  115.  
  116.       The man page for "stat(2)" discusses this.
  117.  
  118. ------------------------------
  119.  
  120. Subject: How do I use "rsh" without having the rsh hang around ... ?
  121. Date: Thu Mar 18 17:16:55 EST 1993
  122.  
  123. 3.2)  How do I use "rsh" without having the rsh hang around until the
  124.       remote command has completed?
  125.  
  126.       (See note in question 2.7 about what "rsh" we're talking about.)
  127.  
  128.       The obvious answers fail:
  129.             rsh machine command &
  130.       or      rsh machine 'command &'
  131.  
  132.       For instance, try doing   rsh machine 'sleep 60 &' and you'll see
  133.       that the 'rsh' won't exit right away.  It will wait 60 seconds
  134.       until the remote 'sleep' command finishes, even though that
  135.       command was started in the background on the remote machine.  So
  136.       how do you get the 'rsh' to exit immediately after the 'sleep' is
  137.       started?
  138.  
  139.       The solution - if you use csh on the remote machine:
  140.  
  141.             rsh machine -n 'command >&/dev/null </dev/null &'
  142.  
  143.       If you use sh on the remote machine:
  144.  
  145.             rsh machine -n 'command >/dev/null 2>&1 </dev/null &'
  146.  
  147.       Why?  "-n" attaches rsh's stdin to /dev/null so you could run the
  148.       complete rsh command in the background on the LOCAL machine.
  149.       Thus "-n" is equivalent to another specific "< /dev/null".
  150.       Furthermore, the input/output redirections on the REMOTE machine
  151.       (inside the single quotes) ensure that rsh thinks the session can
  152.       be terminated (there's no data flow any more.)
  153.  
  154.       Note: The file that you redirect to/from on the remote machine
  155.       doesn't have to be /dev/null; any ordinary file will do.
  156.  
  157.       In many cases, various parts of these complicated commands
  158.       aren't necessary.
  159.  
  160. ------------------------------
  161.  
  162. Subject: How do I truncate a file?
  163. Date: Mon, 27 Mar 1995 18:09:10 -0500
  164.  
  165. 3.3)  How do I truncate a file?
  166.  
  167.       The BSD function ftruncate() sets the length of a file.
  168.       (But not all versions behave identically.)  Other Unix variants
  169.       all seem to support some version of truncation as well.
  170.  
  171.       For systems which support the ftruncate function, there are
  172.       three known behaviours: 
  173.  
  174.       BSD 4.2 - Ultrix, SGI, LynxOS
  175.               - truncation doesn't grow file
  176.               - truncation doesn't move file pointer
  177.  
  178.  
  179.       BSD 4.3 - SunOS, Solaris, OSF/1, HP/UX, Amiga
  180.               - truncation can grow file
  181.               - truncation doesn't move file pointer
  182.  
  183.       Cray    - UniCOS 7, UniCOS 8
  184.               - truncation doesn't grow file
  185.               - truncation changes file pointer
  186.  
  187.       Other systems come in four varieties:
  188.  
  189.       F_CHSIZE - Only SCO
  190.                - some systems define F_CHSIZE but don't support it
  191.                - behaves like BSD 4.3
  192.  
  193.       F_FREESP - Only Interative Unix
  194.                - some systems (eg. Interactive Unix) define F_FREESP but
  195.                    don't support it
  196.                - behaves like BSD 4.3
  197.  
  198.       chsize() - QNX and SCO
  199.                - some systems (eg. Interactive Unix) have chsize() but
  200.                    don't support it
  201.                - behaves like BSD 4.3
  202.  
  203.       nothing  - no known systems
  204.                - there will be systems that don't support truncate at all
  205.  
  206.  
  207.       Moderator's Note: I grabbed the functions below a few years back.
  208.                         I can no longer identify the original author.
  209.                         S. Spencer Sun <spencer@ncd.com> has also
  210.                         contributed a version for F_FREESP.
  211.  
  212.       functions for each non-native ftruncate follow
  213.  
  214.       /* ftruncate emulations that work on some System V's.
  215.          This file is in the public domain. */
  216.  
  217.       #include 
  218.       #include 
  219.  
  220.       #ifdef F_CHSIZE
  221.       int
  222.       ftruncate (fd, length)
  223.            int fd;
  224.            off_t length;
  225.       {
  226.         return fcntl (fd, F_CHSIZE, length);
  227.       }
  228.       #else
  229.       #ifdef F_FREESP
  230.       /* The following function was written by
  231.          kucharsk@Solbourne.com (William Kucharski) */
  232.  
  233.       #include 
  234.       #include 
  235.       #include 
  236.  
  237.       int
  238.       ftruncate (fd, length)
  239.            int fd;
  240.            off_t length;
  241.       {
  242.         struct flock fl;
  243.         struct stat filebuf;
  244.  
  245.         if (fstat (fd, &filebuf) < 0)
  246.           return -1;
  247.  
  248.         if (filebuf.st_size < length)
  249.           {
  250.             /* Extend file length. */
  251.             if (lseek (fd, (length - 1), SEEK_SET) < 0)
  252.               return -1;
  253.  
  254.             /* Write a "0" byte. */
  255.             if (write (fd, "", 1) != 1)
  256.               return -1;
  257.           }
  258.         else
  259.           {
  260.             /* Truncate length. */
  261.             fl.l_whence = 0;
  262.             fl.l_len = 0;
  263.             fl.l_start = length;
  264.             fl.l_type = F_WRLCK;      /* Write lock on file space. */
  265.  
  266.             /* This relies on the UNDOCUMENTED F_FREESP argument to
  267.                fcntl, which truncates the file so that it ends at the
  268.                position indicated by fl.l_start.
  269.                Will minor miracles never cease? */
  270.             if (fcntl (fd, F_FREESP, &fl) < 0)
  271.               return -1;
  272.           }
  273.  
  274.         return 0;
  275.       }
  276.       #else
  277.       int
  278.       ftruncate (fd, length)
  279.            int fd;
  280.            off_t length;
  281.       {
  282.         return chsize (fd, length);
  283.       }
  284.       #endif
  285.       #endif
  286.  
  287. ------------------------------
  288.  
  289. Subject: Why doesn't find's "{}" symbol do what I want?
  290. Date: Thu Mar 18 17:16:55 EST 1993
  291.  
  292. 3.4)  Why doesn't find's "{}" symbol do what I want?
  293.  
  294.       "find" has a -exec option that will execute a particular command
  295.       on all the selected files. Find will replace any "{}" it sees
  296.       with the name of the file currently under consideration.
  297.  
  298.       So, some day you might try to use "find" to run a command on
  299.       every file, one directory at a time.  You might try this:
  300.  
  301.         find /path -type d -exec command {}/\* \;
  302.  
  303.       hoping that find will execute, in turn
  304.  
  305.         command directory1/*
  306.         command directory2/*
  307.         ...
  308.  
  309.       Unfortunately, find only expands the "{}" token when it appears
  310.       by itself.  Find will leave anything else like "{}/*" alone, so
  311.       instead of doing what you want, it will do
  312.  
  313.         command {}/*
  314.         command {}/*
  315.         ...
  316.  
  317.       once for each directory.  This might be a bug, it might be a
  318.       feature, but we're stuck with the current behaviour.
  319.  
  320.       So how do you get around this?  One way would be to write a
  321.       trivial little shell script, let's say "./doit", that consists of
  322.  
  323.         command "$1"/*
  324.  
  325.       You could then use
  326.  
  327.         find /path -type d -exec ./doit {} \;
  328.  
  329.       Or if you want to avoid the "./doit" shell script, you can use
  330.  
  331.         find /path -type d -exec sh -c 'command $0/*' {} \;
  332.  
  333.       (This works because within the 'command' of "sh -c 'command' A B C ...",
  334.        $0 expands to A, $1 to B, and so on.)
  335.  
  336.       or you can use the construct-a-command-with-sed trick
  337.  
  338.         find /path -type d -print | sed 's:.*:command &/*:' | sh
  339.  
  340.       If all you're trying to do is cut down on the number of times
  341.       that "command" is executed, you should see if your system has the
  342.       "xargs" command.  Xargs reads arguments one line at a time from
  343.       the standard input and assembles as many of them as will fit into
  344.       one command line.  You could use
  345.  
  346.         find /path -print | xargs command
  347.  
  348.       which would result in one or more executions of
  349.  
  350.         command file1 file2 file3 file4 dir1/file1 dir1/file2
  351.  
  352.       Unfortunately this is not a perfectly robust or secure solution.
  353.       Xargs expects its input lines to be terminated with newlines, so
  354.       it will be confused by files with odd characters such as newlines
  355.       in their names.
  356.  
  357. ------------------------------
  358.  
  359. Subject: How do I set the permissions on a symbolic link?
  360. Date: Thu Mar 18 17:16:55 EST 1993
  361.  
  362. 3.5)  How do I set the permissions on a symbolic link?
  363.  
  364.       Permissions on a symbolic link don't really mean anything.  The
  365.       only permissions that count are the permissions on the file that
  366.       the link points to.
  367.  
  368. ------------------------------
  369.  
  370. Subject: How do I "undelete" a file?
  371. Date: Thu Mar 18 17:16:55 EST 1993
  372.  
  373. 3.6)  How do I "undelete" a file?
  374.  
  375.       Someday, you are going to accidentally type something like
  376.       "rm * .foo", and find you just deleted "*" instead of "*.foo".
  377.       Consider it a rite of passage.
  378.  
  379.       Of course, any decent systems administrator should be doing
  380.       regular backups.  Check with your sysadmin to see if a recent
  381.       backup copy of your file is available.  But if it isn't, read
  382.       on.
  383.  
  384.       For all intents and purposes, when you delete a file with "rm" it
  385.       is gone.  Once you "rm" a file, the system totally forgets which
  386.       blocks scattered around the disk were part of your file.  Even
  387.       worse, the blocks from the file you just deleted are going to be
  388.       the first ones taken and scribbled upon when the system needs
  389.       more disk space.  However, never say never.  It is theoretically
  390.       possible *if* you shut down the system immediately after the "rm"
  391.       to recover portions of the data.  However, you had better have a
  392.       very wizardly type person at hand with hours or days to spare to
  393.       get it all back.
  394.  
  395.       Your first reaction when you "rm" a file by mistake is why not
  396.       make a shell alias or procedure which changes "rm" to move files
  397.       into a trash bin rather than delete them?  That way you can
  398.       recover them if you make a mistake, and periodically clean out
  399.       your trash bin.  Two points:  first, this is generally accepted
  400.       as a *bad* idea.  You will become dependent upon this behaviour
  401.       of "rm", and you will find yourself someday on a normal system
  402.       where "rm" is really "rm", and you will get yourself in trouble.
  403.       Second, you will eventually find that the hassle of dealing with
  404.       the disk space and time involved in maintaining the trash bin, it
  405.       might be easier just to be a bit more careful with "rm".  For
  406.       starters, you should look up the "-i" option to "rm" in your
  407.       manual.
  408.  
  409.       If you are still undaunted, then here is a possible simple
  410.       answer.  You can create yourself a "can" command which moves
  411.       files into a trashcan directory. In csh(1) you can place the
  412.       following commands in the ".login" file in your home directory:
  413.  
  414.         alias can       'mv \!* ~/.trashcan'       # junk file(s) to trashcan
  415.         alias mtcan     'rm -f ~/.trashcan/*'      # irretrievably empty trash
  416.         if ( ! -d ~/.trashcan ) mkdir ~/.trashcan  # ensure trashcan exists
  417.  
  418.       You might also want to put a:
  419.  
  420.         rm -f ~/.trashcan/*
  421.  
  422.       in the ".logout" file in your home directory to automatically
  423.       empty the trash when you log out.  (sh and ksh versions are left
  424.       as an exercise for the reader.)
  425.  
  426.       MIT's Project Athena has produced a comprehensive
  427.       delete/undelete/expunge/purge package, which can serve as a
  428.       complete replacement for rm which allows file recovery.  This
  429.       package was posted to comp.sources.misc (volume 17, issue
  430.       023-026)
  431.  
  432. ------------------------------
  433.  
  434. Subject: How can a process detect if it's running in the background?
  435. Date: Thu Mar 18 17:16:55 EST 1993
  436.  
  437. 3.7)  How can a process detect if it's running in the background?
  438.  
  439.       First of all: do you want to know if you're running in the
  440.       background, or if you're running interactively? If you're
  441.       deciding whether or not you should print prompts and the like,
  442.       that's probably a better criterion. Check if standard input
  443.       is a terminal:
  444.  
  445.             sh: if [ -t 0 ]; then ... fi
  446.             C: if(isatty(0)) { ... }
  447.  
  448.       In general, you can't tell if you're running in the background.
  449.       The fundamental problem is that different shells and different
  450.       versions of UNIX have different notions of what "foreground" and
  451.       "background" mean - and on the most common type of system with a
  452.       better-defined notion of what they mean, programs can be moved
  453.       arbitrarily between foreground and background!
  454.  
  455.       UNIX systems without job control typically put a process into the
  456.       background by ignoring SIGINT and SIGQUIT and redirecting the
  457.       standard input to "/dev/null"; this is done by the shell.
  458.  
  459.       Shells that support job control, on UNIX systems that support job
  460.       control, put a process into the background by giving it a process
  461.       group ID different from the process group to which the terminal
  462.       belongs.  They move it back into the foreground by setting the
  463.       terminal's process group ID to that of the process.  Shells that
  464.       do *not* support job control, on UNIX systems that support job
  465.       control, typically do what shells do on systems that don't
  466.       support job control.
  467.  
  468. ------------------------------
  469.  
  470. Subject: Why doesn't redirecting a loop work as intended?  (Bourne shell)
  471. Date: Thu Mar 18 17:16:55 EST 1993
  472.  
  473. 3.8)  Why doesn't redirecting a loop work as intended?  (Bourne shell)
  474.  
  475.       Take the following example:
  476.  
  477.         foo=bar
  478.  
  479.         while read line
  480.         do
  481.                 # do something with $line
  482.                 foo=bletch
  483.         done < /etc/passwd
  484.  
  485.         echo "foo is now: $foo"
  486.  
  487.       Despite the assignment ``foo=bletch'' this will print
  488.       ``foo is now: bar'' in many implementations of the Bourne shell.
  489.       Why?  Because of the following, often undocumented, feature of
  490.       historic Bourne shells: redirecting a control structure (such as
  491.       a loop, or an ``if'' statement) causes a subshell to be created,
  492.       in which the structure is executed; variables set in that
  493.       subshell (like the ``foo=bletch'' assignment) don't affect the
  494.       current shell, of course.
  495.  
  496.       The POSIX 1003.2 Shell and Tools Interface standardization
  497.       committee forbids the behaviour described above, i.e. in P1003.2
  498.       conformant Bourne shells the example will print ``foo is now:
  499.       bletch''.
  500.  
  501.       In historic (and P1003.2 conformant) implementations you can use
  502.       the following `trick' to get around the redirection problem:
  503.  
  504.         foo=bar
  505.  
  506.         # make file descriptor 9 a duplicate of file descriptor 0 (stdin);
  507.         # then connect stdin to /etc/passwd; the original stdin is now
  508.         # `remembered' in file descriptor 9; see dup(2) and sh(1)
  509.         exec 9<&0 < /etc/passwd
  510.  
  511.         while read line
  512.         do
  513.                 # do something with $line
  514.                 foo=bletch
  515.         done
  516.  
  517.         # make stdin a duplicate of file descriptor 9, i.e. reconnect
  518.         # it to the original stdin; then close file descriptor 9
  519.         exec 0<&9 9<&-
  520.  
  521.         echo "foo is now: $foo"
  522.  
  523.       This should always print ``foo is now: bletch''.
  524.       Right, take the next example:
  525.  
  526.         foo=bar
  527.  
  528.         echo bletch | read foo
  529.  
  530.         echo "foo is now: $foo"
  531.  
  532.       This will print ``foo is now: bar'' in many implementations,
  533.       ``foo is now: bletch'' in some others.  Why?  Generally each part
  534.       of a pipeline is run in a different subshell; in some
  535.       implementations though, the last command in the pipeline is made
  536.       an exception: if it is a builtin command like ``read'', the
  537.       current shell will execute it, else another subshell is created.
  538.  
  539.       POSIX 1003.2 allows both behaviours so portable scripts cannot
  540.       depend on any of them.
  541.  
  542. ------------------------------
  543.  
  544. Subject: How do I run ... interactive programs from a shell script ... ?
  545. Date: Thu Mar 18 17:16:55 EST 1993
  546.  
  547. 3.9)  How do I run 'passwd', 'ftp', 'telnet', 'tip' and other interactive
  548.       programs from a shell script or in the background?
  549.  
  550.       These programs expect a terminal interface.  Shells makes no
  551.       special provisions to provide one.  Hence, such programs cannot
  552.       be automated in shell scripts.
  553.  
  554.       The 'expect' program provides a programmable terminal interface
  555.       for automating interaction with such programs.  The following
  556.       expect script is an example of a non-interactive version of
  557.       passwd(1).
  558.  
  559.         # username is passed as 1st arg, password as 2nd
  560.         set password [index $argv 2]
  561.         spawn passwd [index $argv 1]
  562.         expect "*password:"
  563.         send "$password\r"
  564.         expect "*password:"
  565.         send "$password\r"
  566.         expect eof
  567.  
  568.       expect can partially automate interaction which is especially
  569.       useful for telnet, rlogin, debuggers or other programs that have
  570.       no built-in command language.  The distribution provides an
  571.       example script to rerun rogue until a good starting configuration
  572.       appears.  Then, control is given back to the user to enjoy the game.
  573.  
  574.       Fortunately some programs have been written to manage the
  575.       connection to a pseudo-tty so that you can run these sorts of
  576.       programs in a script.
  577.  
  578.       To get expect, email "send pub/expect/expect.shar.Z" to
  579.       library@cme.nist.gov or anonymous ftp same from
  580.       ftp.cme.nist.gov.
  581.  
  582.       Another solution is provided by the pty 4.0 program, which runs a
  583.       program under a pseudo-tty session and was posted to
  584.       comp.sources.unix, volume 25.  A pty-based solution using named
  585.       pipes to do the same as the above might look like this:
  586.  
  587.         #!/bin/sh
  588.         /etc/mknod out.$$ p; exec 2>&1
  589.         ( exec 4<out.$$; rm -f out.$$
  590.         <&4 waitfor 'password:'
  591.             echo "$2"
  592.         <&4 waitfor 'password:'
  593.             echo "$2"
  594.         <&4 cat >/dev/null
  595.         ) | ( pty passwd "$1" >out.$$ )
  596.  
  597.       Here, 'waitfor' is a simple C program that searches for
  598.       its argument in the input, character by character.
  599.  
  600.       A simpler pty solution (which has the drawback of not
  601.       synchronizing properly with the passwd program) is
  602.  
  603.         #!/bin/sh
  604.         ( sleep 5; echo "$2"; sleep 5; echo "$2") | pty passwd "$1"
  605.  
  606. ------------------------------
  607.  
  608. Subject: How do I find the process ID of a program with a particular name ... ?
  609. Date: Thu Mar 18 17:16:55 EST 1993
  610.  
  611. 3.10) How do I find the process ID of a program with a particular name
  612.       from inside a shell script or C program?
  613.  
  614.       In a shell script:
  615.  
  616.       There is no utility specifically designed to map between program
  617.       names and process IDs.  Furthermore, such mappings are often
  618.       unreliable, since it's possible for more than one process to have
  619.       the same name, and since it's possible for a process to change
  620.       its name once it starts running.  However, a pipeline like this
  621.       can often be used to get a list of processes (owned by you) with
  622.       a particular name:
  623.  
  624.             ps ux | awk '/name/ && !/awk/ {print $2}'
  625.  
  626.       You replace "name" with the name of the process for which you are
  627.       searching.
  628.  
  629.       The general idea is to parse the output of ps, using awk or grep
  630.       or other utilities, to search for the lines with the specified
  631.       name on them, and print the PID's for those lines.  Note that the
  632.       "!/awk/" above prevents the awk process for being listed.
  633.  
  634.       You may have to change the arguments to ps, depending on what
  635.       kind of Unix you are using.
  636.  
  637.       In a C program:
  638.  
  639.       Just as there is no utility specifically designed to map between
  640.       program names and process IDs, there are no (portable) C library
  641.       functions to do it either.
  642.  
  643.       However, some vendors provide functions for reading Kernel
  644.       memory; for example, Sun provides the "kvm_" functions, and Data
  645.       General provides the "dg_" functions.  It may be possible for any
  646.       user to use these, or they may only be useable by the super-user
  647.       (or a user in group "kmem") if read-access to kernel memory on
  648.       your system is restricted.  Furthermore, these functions are
  649.       often not documented or documented badly, and might change from
  650.       release to release.
  651.  
  652.       Some vendors provide a "/proc" filesystem, which appears as a
  653.       directory with a bunch of filenames in it.  Each filename is a
  654.       number, corresponding to a process ID, and you can open the file
  655.       and read it to get information about the process.  Once again,
  656.       access to this may be restricted, and the interface to it may
  657.       change from system to system.
  658.  
  659.       If you can't use vendor-specific library functions, and you
  660.       don't have /proc, and you still want to do this completely
  661.       in C, you
  662.       are going to have to do the rummaging through kernel memory
  663.       yourself.  For a good example of how to do this on many systems,
  664.       see the sources to "ofiles", available in the comp.sources.unix
  665.       archives.  (A package named "kstuff" to help with kernel
  666.       rummaging was posted to alt.sources in May 1991 and is also
  667.       available via anonymous ftp as
  668.       usenet/alt.sources/articles/{329{6,7,8,9},330{0,1}}.Z from
  669.       wuarchive.wustl.edu.)
  670.  
  671. ------------------------------
  672.  
  673. Subject: How do I check the exit status of a remote command executed via "rsh"?
  674. Date: Thu Mar 18 17:16:55 EST 1993
  675.  
  676. 3.11) How do I check the exit status of a remote command
  677.       executed via "rsh" ?
  678.  
  679.       This doesn't work:
  680.  
  681.         rsh some-machine some-crummy-command || echo "Command failed"
  682.  
  683.       The exit status of 'rsh' is 0 (success) if the rsh program
  684.       itself completed successfully, which probably isn't what
  685.       you wanted.
  686.  
  687.       If you want to check on the exit status of the remote program,
  688.       you can try using Maarten Litmaath's 'ersh' script, which was
  689.       posted to alt.sources in October 1994.  ersh is a shell script
  690.       that calls rsh, arranges for the remote machine to echo the
  691.       status of the command after it completes, and exits with that
  692.       status.
  693.  
  694. ------------------------------
  695.  
  696. Subject: Is it possible to pass shell variable settings into an awk program?
  697. Date: Thu Mar 18 17:16:55 EST 1993
  698.  
  699. 3.12) Is it possible to pass shell variable settings into an awk program?
  700.  
  701.       There are two different ways to do this.  The first involves
  702.       simply expanding the variable where it is needed in the program.
  703.       For example, to get a list of all ttys you're using:
  704.  
  705.         who | awk '/^'"$USER"'/ { print $2 }'                           (1)
  706.  
  707.       Single quotes are usually used to enclose awk programs because
  708.       the character '$' is often used in them, and '$' will be
  709.       interpreted by the shell if enclosed inside double quotes, but
  710.       not if enclosed inside single quotes.  In this case, we *want*
  711.       the '$' in "$USER" to be interpreted by the shell, so we close
  712.       the single quotes and then put the "$USER" inside double quotes.
  713.       Note that there are no spaces in any of that, so the shell will
  714.       see it all as one argument.  Note, further, that the double
  715.       quotes probably aren't necessary in this particular case (i.e. we
  716.       could have done
  717.  
  718.         who | awk '/^'$USER'/ { print $2 }'                             (2)
  719.  
  720.       ), but they should be included nevertheless because they are
  721.       necessary when the shell variable in question contains special
  722.       characters or spaces.
  723.  
  724.       The second way to pass variable settings into awk is to use an
  725.       often undocumented feature of awk which allows variable settings
  726.       to be specified as "fake file names" on the command line.  For
  727.       example:
  728.  
  729.         who | awk '$1 == user { print $2 }' user="$USER" -              (3)
  730.  
  731.       Variable settings take effect when they are encountered on the
  732.       command line, so, for example, you could instruct awk on how to
  733.       behave for different files using this technique.  For example:
  734.  
  735.         awk '{ program that depends on s }' s=1 file1 s=0 file2         (4)
  736.  
  737.       Note that some versions of awk will cause variable settings
  738.       encountered before any real filenames to take effect before the
  739.       BEGIN block is executed, but some won't so neither way should be
  740.       relied upon.
  741.  
  742.       Note, further, that when you specify a variable setting, awk
  743.       won't automatically read from stdin if no real files are
  744.       specified, so you need to add a "-" argument to the end of your
  745.       command, as I did at (3) above.
  746.  
  747.       A third option is to use a newer version of awk (nawk), which allows
  748.       direct access to environment vairables.  Eg.
  749.  
  750.         nawk 'END { print "Your path variable is " ENVIRON["PATH"] }' /dev/null
  751.  
  752. ------------------------------
  753.  
  754. Subject: How do I get rid of zombie processes that persevere?
  755. >From: Jonathan I. Kamens
  756. >From: casper@fwi.uva.nl (Casper Dik)
  757. Date: Thu, 09 Sep 93 16:39:58 +0200
  758.  
  759. 3.13) How do I get rid of zombie processes that persevere?
  760.  
  761.       Unfortunately, it's impossible to generalize how the death of
  762.       child processes should behave, because the exact mechanism varies
  763.       over the various flavors of Unix.
  764.  
  765.       First of all, by default, you have to do a wait() for child
  766.       processes under ALL flavors of Unix.  That is, there is no flavor
  767.       of Unix that I know of that will automatically flush child
  768.       processes that exit, even if you don't do anything to tell it to
  769.       do so.
  770.  
  771.       Second, under some SysV-derived systems, if you do
  772.       "signal(SIGCHLD, SIG_IGN)" (well, actually, it may be SIGCLD
  773.       instead of SIGCHLD, but most of the newer SysV systems have
  774.       "#define SIGCHLD SIGCLD" in the header files), then child
  775.       processes will be cleaned up automatically, with no further
  776.       effort in your part.  The best way to find out if it works at
  777.       your site is to try it, although if you are trying to write
  778.       portable code, it's a bad idea to rely on this in any case.
  779.       Unfortunately, POSIX doesn't allow you to do this; the behavior
  780.       of setting the SIGCHLD to SIG_IGN under POSIX is undefined, so
  781.       you can't do it if your program is supposed to be
  782.       POSIX-compliant.
  783.  
  784.       So, what's the POSIX way? As mentioned earlier, you must
  785.       install a signal handler and wait. Under POSIX signal handlers
  786.       are installed with sigaction. Since you are not interested in
  787.       ``stopped'' children, only in terminated children, add SA_NOCLDSTOP
  788.       to sa_flags.  Waiting without blocking is done with waitpid().
  789.       The first argument to waitpid should be -1 (wait for any pid),
  790.       the third should be WNOHANG. This is the most portable way
  791.       and is likely to become more portable in future.
  792.  
  793.       If your systems doesn't support POSIX, there's a number of ways.
  794.       The easiest way is signal(SIGCHLD, SIG_IGN), if it works.
  795.       If SIG_IGN cannot be used to force automatic clean-up, then you've
  796.       got to write a signal handler to do it.  It isn't easy at all to
  797.       write a signal handler that does things right on all flavors of
  798.       Unix, because of the following inconsistencies:
  799.  
  800.       On some flavors of Unix, the SIGCHLD signal handler is called if
  801.       one *or more* children have died.  This means that if your signal
  802.       handler only does one wait() call, then it won't clean up all of
  803.       the children.  Fortunately, I believe that all Unix flavors for
  804.       which this is the case have available to the programmer the
  805.       wait3() or waitpid() call, which allows the WNOHANG option to
  806.       check whether or not there are any children waiting to be cleaned
  807.       up.  Therefore, on any system that has wait3()/waitpid(), your
  808.       signal handler should call wait3()/waitpid() over and over again
  809.       with the WNOHANG option until there are no children left to clean
  810.       up. Waitpid() is the preferred interface, as it is in POSIX.
  811.  
  812.       On SysV-derived systems, SIGCHLD signals are regenerated if there
  813.       are child processes still waiting to be cleaned up after you exit
  814.       the SIGCHLD signal handler.  Therefore, it's safe on most SysV
  815.       systems to assume when the signal handler gets called that you
  816.       only have to clean up one signal, and assume that the handler
  817.       will get called again if there are more to clean up after it
  818.       exits.
  819.  
  820.       On older systems, there is no way to prevent signal handlers
  821.       from being automatically reset to SIG_DFL when the signal
  822.       handler gets called.  On such systems, you have to put
  823.       "signal(SIGCHILD, catcher_func)" (where "catcher_func" is the
  824.       name of the handler function) as the last thing in the signal
  825.       handler, so that it gets reset.
  826.  
  827.       Fortunately, newer implementations allow signal handlers to be
  828.       installed without being reset to SIG_DFL when the handler
  829.       function is called.  To get around this problem, on systems that
  830.       do not have wait3()/waitpid() but do have SIGCLD, you need to
  831.       reset the signal handler with a call to signal() after doing at
  832.       least one wait() within the handler, each time it is called.  For
  833.       backward compatibility reasons, System V will keep the old
  834.       semantics (reset handler on call) of signal().  Signal handlers
  835.       that stick can be installed with sigaction() or sigset().
  836.  
  837.       The summary of all this is that on systems that have waitpid()
  838.       (POSIX) or wait3(), you should use that and your signal handler
  839.       should loop, and on systems that don't, you should have one call
  840.       to wait() per invocation of the signal handler.
  841.  
  842.       One more thing -- if you don't want to go through all of this
  843.       trouble, there is a portable way to avoid this problem, although
  844.       it is somewhat less efficient.  Your parent process should fork,
  845.       and then wait right there and then for the child process to
  846.       terminate.  The child process then forks again, giving you a
  847.       child and a grandchild.  The child exits immediately (and hence
  848.       the parent waiting for it notices its death and continues to
  849.       work), and the grandchild does whatever the child was originally
  850.       supposed to.  Since its parent died, it is inherited by init,
  851.       which will do whatever waiting is needed.  This method is
  852.       inefficient because it requires an extra fork, but is pretty much
  853.       completely portable.
  854.  
  855. ------------------------------
  856.  
  857. Subject: How do I get lines from a pipe ... instead of only in larger blocks?
  858. >From: Jonathan I. Kamens
  859. Date: Sun, 16 Feb 92 20:59:28 -0500
  860.  
  861. 3.14) How do I get lines from a pipe as they are written instead of only in
  862.       larger blocks?
  863.  
  864.       The stdio library does buffering differently depending on whether
  865.       it thinks it's running on a tty.  If it thinks it's on a tty, it
  866.       does buffering on a per-line basis; if not, it uses a larger
  867.       buffer than one line.
  868.  
  869.       If you have the source code to the client whose buffering you
  870.       want to disable, you can use setbuf() or setvbuf() to change the
  871.       buffering.
  872.  
  873.       If not, the best you can do is try to convince the program that
  874.       it's running on a tty by running it under a pty, e.g. by using
  875.       the "pty" program mentioned in question 3.9.
  876.  
  877. ------------------------------
  878.  
  879. Subject: How do I get the date into a filename?
  880. >From: melodie neal <melodie@comtech.ct.oz.au>
  881. Date: Fri, 7 Oct 1994 09:27:33 -0400
  882.  
  883. 3.15) How do I get the date into a filename?
  884.  
  885.       This isn't hard, but it is a bit cryptic at first sight.  Let's
  886.       begin with the date command itself:  date can take a formatting
  887.       string, to modify the way in which the date info is printed.  The
  888.       formatting string has to be enclosed in quotes, to stop the shell
  889.       trying to interpret it before the date command itself gets it.
  890.       Try this:
  891.  
  892.         date '+%d%m%y'
  893.  
  894.       you should get back something like 130994.  If you want to
  895.       punctuate this, just put the characters you would like to use in
  896.       the formatting string (NO SLASHES '/'):
  897.  
  898.         date '+%d.%m.%y'
  899.  
  900.       There are lots of token you can use in the formatting string:
  901.       have a look at the man page for date to find out about them.
  902.  
  903.       Now, getting this into a file name.  Let's say that we want to
  904.       create files called report.130994 (or whatever the date is today):
  905.  
  906.         FILENAME=report.`date '+%d%m%y'`
  907.  
  908.       Notice that we are using two sets of quotes here:  the inner set
  909.       are to protect the formatting string from premature
  910.       interpretation;  the outer set are to tell the shell to execute
  911.       the enclosed command, and substitute the result into the
  912.       expression (command substitution).
  913.  
  914. ------------------------------
  915.  
  916. Subject: Why do some scripts start with #! ... ?
  917. >From: chip@@chinacat.unicom.com (Chip Rosenthal)
  918. Date: Tue, 14 Jul 1992 21:31:54 GMT
  919.  
  920. 3.16) Why do some scripts start with #! ... ?
  921.  
  922.       Chip Rosenthal has answered a closely related question in
  923.       comp.unix.xenix in the past.
  924.  
  925.       I think what confuses people is that there exist two different
  926.       mechanisms, both spelled with the letter `#'.  They both solve the
  927.       same problem over a very restricted set of cases -- but they are
  928.       none the less different.
  929.  
  930.       Some background.  When the UNIX kernel goes to run a program (one
  931.       of the exec() family of system calls), it takes a peek at the
  932.       first 16 bits of the file.  Those 16 bits are called a `magic
  933.       number'.  First, the magic number prevents the kernel from doing
  934.       something silly like trying to execute your customer database
  935.       file.  If the kernel does not recognize the magic number then it
  936.       complains with an ENOEXEC error.  It will execute the program only
  937.       if the magic number is recognizable.
  938.  
  939.       Second, as time went on and different executable file formats were
  940.       introduced, the magic number not only told the kernel *if* it
  941.       could execute the file, but also *how* to execute the file.  For
  942.       example, if you compile a program on an SCO XENIX/386 system and
  943.       carry the binary over to a SysV/386 UNIX system, the kernel will
  944.       recognize the magic number and say `Aha!  This is an x.out
  945.       binary!' and configure itself to run with XENIX compatible system
  946.       calls.
  947.  
  948.       Note that the kernel can only run binary executable images.  So
  949.       how, you might ask, do scripts get run?  After all, I can type
  950.       `my.script' at a shell prompt and I don't get an ENOEXEC error.
  951.       Script execution is done not by the kernel, but by the shell.  The
  952.       code in the shell might look something like:
  953.  
  954.         /* try to run the program */
  955.         execl(program, basename(program), (char *)0);
  956.  
  957.         /* the exec failed -- maybe it is a shell script? */
  958.         if (errno == ENOEXEC)
  959.             execl ("/bin/sh", "sh", "-c", program, (char *)0);
  960.  
  961.         /* oh no mr bill!! */
  962.         perror(program);
  963.         return -1;
  964.  
  965.             (This example is highly simplified.  There is a lot
  966.             more involved, but this illustrates the point I'm
  967.             trying to make.)
  968.  
  969.       If execl() is successful in starting the program then the code
  970.       beyond the execl() is never executed.  In this example, if we can
  971.       execl() the `program' then none of the stuff beyond it is run.
  972.       Instead the system is off running the binary `program'.
  973.  
  974.       If, however, the first execl() failed then this hypothetical shell
  975.       looks at why it failed.  If the execl() failed because `program'
  976.       was not recognized as a binary executable, then the shell tries to
  977.       run it as a shell script.
  978.  
  979.       The Berkeley folks had a neat idea to extend how the kernel starts
  980.       up programs.  They hacked the kernel to recognize the magic number
  981.       `#!'.  (Magic numbers are 16-bits and two 8-bit characters makes
  982.       16 bits, right?)  When the `#!' magic number was recognized, the
  983.       kernel would read in the rest of the line and treat it as a
  984.       command to run upon the contents of the file.  With this hack you
  985.       could now do things like:
  986.  
  987.         #! /bin/sh
  988.  
  989.         #! /bin/csh
  990.  
  991.         #! /bin/awk -F:
  992.  
  993.       This hack has existed solely in the Berkeley world, and has
  994.       migrated to USG kernels as part of System V Release 4.  Prior to
  995.       V.4, unless the vendor did some special value added, the kernel
  996.       does not have the capability of doing anything other than loading
  997.       and starting a binary executable image.
  998.  
  999.       Now, lets rewind a few years, to the time when more and more folks
  1000.       running USG based unices were saying `/bin/sh sucks as an
  1001.       interactive user interface!  I want csh!'.  Several vendors did
  1002.       some value added magic and put csh in their distribution, even
  1003.       though csh was not a part of the USG UNIX distribution.
  1004.  
  1005.       This, however, presented a problem.  Let's say you switch your
  1006.       login shell to /bin/csh.  Let's further suppose that you are a
  1007.       cretin and insist upon programming csh scripts.  You'd certainly
  1008.       want to be able to type `my.script' and get it run, even though it
  1009.       is a csh script.  Instead of pumping it through /bin/sh, you want
  1010.       the script to be started by running:
  1011.  
  1012.         execl ("/bin/csh", "csh", "-c", "my.script", (char *)0);
  1013.  
  1014.       But what about all those existing scripts -- some of which are
  1015.       part of the system distribution?  If they started getting run by
  1016.       csh then things would break.  So you needed a way to run some
  1017.       scripts through csh, and others through sh.
  1018.  
  1019.       The solution introduced was to hack csh to take a look at the
  1020.       first character of the script you are trying to run.  If it was a
  1021.       `#' then csh would try to run the script through /bin/csh,
  1022.       otherwise it would run the script through /bin/sh.  The example
  1023.       code from the above might now look something like:
  1024.  
  1025.         /* try to run the program */
  1026.         execl(program, basename(program), (char *)0);
  1027.  
  1028.         /* the exec failed -- maybe it is a shell script? */
  1029.         if (errno == ENOEXEC && (fp = fopen(program, "r")) != NULL) {
  1030.             i = getc(fp);
  1031.             (void) fclose(fp);
  1032.             if (i == '#')
  1033.                 execl ("/bin/csh", "csh", "-c", program, (char *)0);
  1034.             else
  1035.                 execl ("/bin/sh", "sh", "-c", program, (char *)0);
  1036.         }
  1037.  
  1038.         /* oh no mr bill!! */
  1039.         perror(program);
  1040.         return -1;
  1041.  
  1042.       Two important points.  First, this is a `csh' hack.  Nothing has
  1043.       been changed in the kernel and nothing has been changed in the
  1044.       other shells.  If you try to execl() a script, whether or not it
  1045.       begins with `#', you will still get an ENOEXEC failure.  If you
  1046.       try to run a script beginning with `#' from something other than
  1047.       csh (e.g. /bin/sh), then it will be run by sh and not csh.
  1048.  
  1049.       Second, the magic is that either the script begins with `#' or it
  1050.       doesn't begin with `#'.  What makes stuff like `:' and `: /bin/sh'
  1051.       at the front of a script magic is the simple fact that they are
  1052.       not `#'.  Therefore, all of the following are identical at the
  1053.       start of a script:
  1054.  
  1055.         :
  1056.  
  1057.         : /bin/sh
  1058.  
  1059.                         <--- a blank line
  1060.  
  1061.         : /usr/games/rogue
  1062.  
  1063.         echo "Gee...I wonder what shell I am running under???"
  1064.  
  1065.       In all these cases, all shells will try to run the script with /bin/sh.
  1066.  
  1067.       Similarly, all of the following are identical at the start of a script:
  1068.  
  1069.         #
  1070.  
  1071.         # /bin/csh
  1072.  
  1073.         #! /bin/csh
  1074.  
  1075.         #! /bin/sh
  1076.  
  1077.         # Gee...I wonder what shell I am running under???
  1078.  
  1079.       All of these start with a `#'.  This means that the script will be
  1080.       run by csh *only* if you try to start it from csh, otherwise it
  1081.       will be run by /bin/sh.
  1082.  
  1083.             (Note:  if you are running ksh, substitute `ksh' for
  1084.             `sh' in the above.  The Korn shell is theoretically
  1085.             compatible with Bourne shell, so it tries to run these
  1086.             scripts itself.  Your mileage may vary on some of the
  1087.             other available shells such as zsh, bash, etc.)
  1088.  
  1089.       Obviously, if you've got support for `#!' in the kernel then the
  1090.       `#' hack becomes superfluous.  In fact, it can be dangerous
  1091.       because it creates confusion over what should happen with `#! /bin/sh'.
  1092.  
  1093.       The `#!' handling is becoming more and more prevelant.  System V
  1094.       Release 4 picks up a number of the Berkeley features, including
  1095.       this.  Some System V Release 3.2 vendors are hacking in some of
  1096.       the more visible V.4 features such as this and trying to convince
  1097.       you this is sufficient and you don't need things like real,
  1098.       working streams or dynamically adjustable kernel parameters.
  1099.  
  1100.       XENIX does not support `#!'.  The XENIX /bin/csh does have the `#'
  1101.       hack.  Support for `#!' in XENIX would be nice, but I wouldn't
  1102.       hold my breath waiting for it.
  1103.  
  1104. ------------------------------
  1105.  
  1106. End of unix/faq Digest part 3 of 7
  1107. **********************************
  1108.  
  1109. -- 
  1110. Ted Timar - tmatimar@isgtec.com
  1111. ISG Technologies Inc., 6509 Airport Road, Mississauga, Ontario, Canada L4V 1S7
  1112.