home *** CD-ROM | disk | FTP | other *** search
/ ftp.pasteur.org/FAQ/ / ftp-pasteur-org-FAQ.zip / FAQ / unix-faq / programmer / faq < prev    next >
Encoding:
Internet Message Format  |  2003-10-25  |  131.5 KB

  1. Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!newsfeed.stanford.edu!headwall.stanford.edu!newshub.sdsu.edu!elnk-nf2-pas!elnk-pas-nf1!newsfeed.earthlink.net!sn-xit-02!sn-xit-06!sn-xit-08!supernews.com!news-spur.riddles.org.uk!newsmonster
  2. From: Andrew Gierth <andrew@erlenstar.demon.co.uk>
  3. Newsgroups: comp.unix.programmer,comp.answers,news.answers
  4. Subject: Unix Programming FAQ (v1.37)
  5. Supersedes: <auto-cup-faq-000135-20031009194001@erlenstar.demon.co.uk>
  6. Followup-To: poster
  7. Date: 23 Oct 2003 19:40:02 +0100
  8. Organization: none at all
  9. Lines: 3697
  10. Approved: news-answers-request@MIT.EDU
  11. Expires: 11 Nov 2003 18:40:01 -0000
  12. Message-ID: <auto-cup-faq-000136-20031023194001@erlenstar.demon.co.uk>
  13. Summary: This posting contains answers to frequently-asked questions regarding
  14.      programming in the Unix environment.
  15. Keywords: unix faq
  16. X-Complaints-To: abuse@news-spur.riddles.org.uk
  17. X-Post-Filter: postfilter v0.6 alpha
  18. Xref: senator-bedfellow.mit.edu comp.unix.programmer:162040 comp.answers:55215 news.answers:260145
  19.  
  20. Archive-Name: unix-faq/programmer/faq
  21. Comp-unix-programmer-Archive-Name: faq
  22. URL: http://www.erlenstar.demon.co.uk/unix/faq_toc.html
  23. URL: http://www.whitefang.com/unix/faq_toc.html
  24. Posting-Frequency: every 2 weeks
  25. Copyright: Collection Copyright (C) 1997-2000 Andrew Gierth.
  26. Last-Modified: 2000/09/01 06:34:57
  27. Version: 1.37
  28.  
  29. ==============================================================================
  30.  
  31. About this FAQ
  32. **************
  33.  
  34. $Id: rawfaq.texi,v 1.37 2000/09/01 06:34:57 andrew Exp $
  35.  
  36. This FAQ was originally begun by Patrick Horgan in May 1996; I took it over
  37. after it had been lying idle for several months.  I've reorganised it a bit
  38. and added some stuff; I still regard it as `under development'.
  39.  
  40. Comments, suggestions, additions, corrections etc. should be sent to the
  41. maintainer at: <andrew@erlenstar.demon.co.uk>.
  42.  
  43. A hypertext version of this document is available on the WWW. The home site
  44. is located at `http://www.erlenstar.demon.co.uk/unix/faq_toc.html'. A US
  45. mirror site is available at `http://www.whitefang.com/unix/faq_toc.html'.
  46.  
  47. This document is available by FTP from the news.answers archives at
  48. rtfm.mit.edu and its many mirror sites worldwide. The official archive name
  49. is `unix-faq/programmer/faq'. Sites which also archive *.answers posts by
  50. group should also carry the file under the `comp.unix.programmer' directory.
  51.  
  52. Other sources of information are not listed here. You can find pointers to
  53. other FAQs, books, source code etc. in the regular [READ ME FIRST] posting
  54. that should appear weekly in comp.unix.programmer. Administrivia regarding
  55. newsgroup conduct, etc., are also found there; I want to reserve this
  56. document specifically for technical Q's and A's.
  57.  
  58. All contributions have been edited by the maintainer, therefore any errors
  59. or omissions are my responsibility rather than that of the contributor.
  60.  
  61. This FAQ is now maintained as Texinfo source; I'm generating a raw text
  62. version for Usenet using the `makeinfo' program, and an HTML version using
  63. `texi2html'.
  64.  
  65. Copyright (C) 1997, 1998, 1999, 2000 Andrew Gierth. This document may be
  66. distributed freely on Usenet or by email; it may be archived on FTP or WWW
  67. sites that mirror the news.answers archives, provided that all reasonable
  68. efforts are made to ensure that the archive is kept up-to-date.  (This
  69. permission may be withdrawn on an individual basis.)  It may not be
  70. published in any other form, whether in print, on the WWW, on CD-ROM, or in
  71. any other medium, without the express permission of the maintainer.
  72.  
  73. List of contributors in no particular order:
  74.  
  75. Andrew Gierth       <andrew@erlenstar.demon.co.uk>                            
  76. Patrick J. Horgan   withheld                                                  
  77. Stephen Baynes      <stephen.baynes@soton.sc.philips.com>                     
  78. James Raynard       withheld                                                  
  79. Michael F. Quigley  withheld                                                  
  80. Ken Pizzini         withheld                                                  
  81. Thamer Al-Herbish   withheld                                                  
  82. Nick Kew            <nick.kew@pobox.com>                                      
  83. Dan Abarbanel       withheld                                                  
  84. Billy Chambless     <billy@cast.msstate.edu>                                  
  85. Walter Briscoe      <walter@wbriscoe.demon.co.uk>                             
  86. Jim Buchanan        <jbuchana@buchanan1.net>                                  
  87. Dave Plonka         <plonka@doit.wisc.edu>                                    
  88. Daniel Stenberg     withheld                                                  
  89. Ralph Corderoy      <ralph@inputplus.demon.co.uk>                             
  90. Stuart Kemp         withheld                                                  
  91. Sergei Chernev      <ser@nsu.ru>                                              
  92. Bjorn Reese         withheld                                                  
  93. Joe Halpin          <jhalpin@nortel.ca>                                       
  94. Aaron Crane         <aaronc@pobox.com>                                        
  95. Geoff Clare         <gwc@root.co.uk>                                          
  96.  
  97. List of Questions
  98. *****************
  99.  
  100. 1. Process Control
  101.   1.1 Creating new processes: fork()
  102.     1.1.1 What does fork() do?
  103.     1.1.2 What's the difference between fork() and vfork()?
  104.     1.1.3 Why use _exit rather than exit in the child branch of a fork?
  105.   1.2 Environment variables
  106.     1.2.1 How can I get/set an environment variable from a program?
  107.     1.2.2 How can I read the whole environment?
  108.   1.3 How can I sleep for less than a second?
  109.   1.4 How can I get a finer-grained version of alarm()?
  110.   1.5 How can a parent and child process communicate?
  111.   1.6 How do I get rid of zombie processes?
  112.     1.6.1 What is a zombie?
  113.     1.6.2 How do I prevent them from occuring?
  114.   1.7 How do I get my program to act like a daemon?
  115.   1.8 How can I look at process in the system like ps does?
  116.   1.9 Given a pid, how can I tell if it's a running program?
  117.   1.10 What's the return value of system/pclose/waitpid?
  118.   1.11 How do I find out about a process' memory usage?
  119.   1.12 Why do processes never decrease in size?
  120.   1.13 How do I change the name of my program (as seen by `ps')?
  121.   1.14 How can I find a process' executable file?
  122.     1.14.1 So where do I put my configuration files then?
  123.   1.15 Why doesn't my process get SIGHUP when its parent dies?
  124.   1.16 How can I kill all descendents of a process?
  125.  
  126. 2. General File handling (including pipes and sockets)
  127.   2.1 How to manage multiple connections?
  128.     2.1.1 How do I use select()?
  129.     2.1.2 How do I use poll()?
  130.     2.1.3 Can I use SysV IPC at the same time as select or poll?
  131.   2.2 How can I tell when the other end of a connection shuts down?
  132.   2.3 Best way to read directories?
  133.   2.4 How can I find out if someone else has a file open?
  134.   2.5 How do I `lock' a file?
  135.   2.6 How do I find out if a file has been updated by another process?
  136.   2.7 How does the `du' utility work?
  137.   2.8 How do I find the size of a file?
  138.   2.9 How do I expand `~' in a filename like the shell does?
  139.   2.10 What can I do with named pipes (FIFOs)?
  140.     2.10.1 What is a named pipe?
  141.     2.10.2 How do I create a named pipe?
  142.     2.10.3 How do I use a named pipe?
  143.     2.10.4 Can I use a named pipe across NFS?
  144.     2.10.5 Can multiple processes write to the pipe simultaneously?
  145.     2.10.6 Using named pipes in applications
  146.  
  147. 3. Terminal I/O
  148.   3.1 How can I make my program not echo input?
  149.   3.2 How can I read single characters from the terminal?
  150.   3.3 How can I check and see if a key was pressed?
  151.   3.4 How can I move the cursor around the screen?
  152.   3.5 What are pttys?
  153.   3.6 How to handle a serial port or modem?
  154.     3.6.1 Serial device names and types
  155.     3.6.2 Setting up termios flags
  156.       3.6.2.1 c_iflag
  157.       3.6.2.2 c_oflag
  158.       3.6.2.3 c_cflag
  159.       3.6.2.4 c_lflag
  160.       3.6.2.5 c_cc
  161.  
  162. 4. System Information
  163.   4.1 How can I tell how much memory my system has?
  164.   4.2 How do I check a user's password?
  165.     4.2.1 How do I get a user's password?
  166.     4.2.2 How do I get shadow passwords by uid?
  167.     4.2.3 How do I verify a user's password?
  168.  
  169. 5. Miscellaneous programming
  170.   5.1 How do I compare strings using wildcards?
  171.     5.1.1 How do I compare strings using filename patterns?
  172.     5.1.2 How do I compare strings using regular expressions?
  173.   5.2 What's the best way to send mail from a program?
  174.     5.2.1 The simple method: /bin/mail
  175.     5.2.2 Invoking the MTA directly: /usr/lib/sendmail
  176.       5.2.2.1 Supplying the envelope explicitly
  177.       5.2.2.2 Allowing sendmail to deduce the recipients
  178.  
  179. 6. Use of tools
  180.   6.1 How can I debug the children after a fork?
  181.   6.2 How to build library from other libraries?
  182.   6.3 How to create shared libraries / dlls?
  183.   6.4 Can I replace objects in a shared library?
  184.   6.5 How can I generate a stack dump from within a running program?
  185.  
  186. 1. Process Control
  187. ******************
  188.  
  189. 1.1 Creating new processes: fork()
  190. ==================================
  191.  
  192. 1.1.1 What does fork() do?
  193. --------------------------
  194.  
  195.      #include <sys/types.h>
  196.      #include <unistd.h>
  197.      
  198.      pid_t fork(void);
  199.  
  200. The `fork()' function is used to create a new process from an existing
  201. process.  The new process is called the child process, and the existing
  202. process is called the parent.  You can tell which is which by checking the
  203. return value from `fork()'.  The parent gets the child's pid returned to
  204. him, but the child gets 0 returned to him.  Thus this simple code
  205. illustrate's the basics of it.
  206.  
  207.      pid_t pid;
  208.      
  209.      switch (pid = fork())
  210.      {
  211.      case -1:
  212.          /* Here pid is -1, the fork failed */
  213.          /* Some possible reasons are that you're */
  214.          /* out of process slots or virtual memory */
  215.          perror("The fork failed!");
  216.          break;
  217.      
  218.      case 0:
  219.          /* pid of zero is the child */
  220.          /* Here we're the child...what should we do? */
  221.          /* ... */
  222.          /* but after doing it, we should do something like: */
  223.          _exit(0);
  224.      
  225.      default:
  226.          /* pid greater than zero is parent getting the child's pid */
  227.          printf("Child's pid is %d\n",pid);
  228.      }
  229.  
  230. Of course, one can use `if()... else...' instead of `switch()', but the
  231. above form is a useful idiom.
  232.  
  233. Of help when doing this is knowing just what is and is not inherited by the
  234. child.  This list can vary depending on Unix implementation, so take it
  235. with a grain of salt.  Note that the child gets *copies* of these things,
  236. not the real thing.
  237.  
  238. Inherited by the child from the parent:
  239.  
  240.    * process credentials (real/effective/saved UIDs and GIDs)
  241.  
  242.    * environment
  243.  
  244.    * stack
  245.  
  246.    * memory
  247.  
  248.    * open file descriptors (note that the underlying file positions are
  249.      shared between the parent and child, which can be confusing)
  250.  
  251.    * close-on-exec flags
  252.  
  253.    * signal handling settings
  254.  
  255.    * nice value
  256.  
  257.    * scheduler class
  258.  
  259.    * process group ID
  260.  
  261.    * session ID
  262.  
  263.    * current working directory
  264.  
  265.    * root directory
  266.  
  267.    * file mode creation mask (umask)
  268.  
  269.    * resource limits
  270.  
  271.    * controlling terminal
  272.  
  273. Unique to the child:
  274.  
  275.    * process ID
  276.  
  277.    * different parent process ID
  278.  
  279.    * Own copy of file descriptors and directory streams.
  280.  
  281.    * process, text, data and other memory locks are NOT inherited.
  282.  
  283.    * process times, in the tms struct
  284.  
  285.    * resource utilizations are set to 0
  286.  
  287.    * pending signals initialized to the empty set
  288.  
  289.    * timers created by timer_create not inherited
  290.  
  291.    * asynchronous input or output operations not inherited
  292.  
  293. 1.1.2 What's the difference between fork() and vfork()?
  294. -------------------------------------------------------
  295.  
  296. Some systems have a system call `vfork()', which was originally designed as
  297. a lower-overhead version of `fork()'. Since `fork()' involved copying the
  298. entire address space of the process, and was therefore quite expensive, the
  299. `vfork()' function was introduced (in 3.0BSD).
  300.  
  301. *However*, since `vfork()' was introduced, the implementation of `fork()'
  302. has improved drastically, most notably with the introduction of
  303. `copy-on-write', where the copying of the process address space is
  304. transparently faked by allowing both processes to refer to the same
  305. physical memory until either of them modify it. This largely removes the
  306. justification for `vfork()'; indeed, a large proportion of systems now lack
  307. the original functionality of `vfork()' completely. For compatibility,
  308. though, there may still be a `vfork()' call present, that simply calls
  309. `fork()' without attempting to emulate all of the `vfork()' semantics.
  310.  
  311. As a result, it is *very* unwise to actually make use of any of the
  312. differences between `fork()' and `vfork()'. Indeed, it is probably unwise
  313. to use `vfork()' at all, unless you know exactly *why* you want to.
  314.  
  315. The basic difference between the two is that when a new process is created
  316. with `vfork()', the parent process is temporarily suspended, and the child
  317. process might borrow the parent's address space. This strange state of
  318. affairs continues until the child process either exits, or calls
  319. `execve()', at which point the parent process continues.
  320.  
  321. This means that the child process of a `vfork()' must be careful to avoid
  322. unexpectedly modifying variables of the parent process. In particular, the
  323. child process must *not* return from the function containing the `vfork()'
  324. call, and it must *not* call `exit()' (if it needs to exit, it should use
  325. `_exit()'; actually, this is also true for the child of a normal `fork()').
  326.  
  327. 1.1.3 Why use _exit rather than exit in the child branch of a fork?
  328. -------------------------------------------------------------------
  329.  
  330. There are a few differences between `exit()' and `_exit()' that become
  331. significant when `fork()', and especially `vfork()', is used.
  332.  
  333. The basic difference between `exit()' and `_exit()' is that the former
  334. performs clean-up related to user-mode constructs in the library, and calls
  335. user-supplied cleanup functions, whereas the latter performs only the
  336. kernel cleanup for the process.
  337.  
  338. In the child branch of a `fork()', it is normally incorrect to use
  339. `exit()', because that can lead to stdio buffers being flushed twice, and
  340. temporary files being unexpectedly removed. In C++ code the situation is
  341. worse, because destructors for static objects may be run incorrectly.
  342. (There are some unusual cases, like daemons, where the *parent* should call
  343. `_exit()' rather than the child; the basic rule, applicable in the
  344. overwhelming majority of cases, is that `exit()' should be called only once
  345. for each entry into `main'.)
  346.  
  347. In the child branch of a `vfork()', the use of `exit()' is even more
  348. dangerous, since it will affect the state of the *parent* process.
  349.  
  350. 1.2 Environment variables
  351. =========================
  352.  
  353. 1.2.1 How can I get/set an environment variable from a program?
  354. ---------------------------------------------------------------
  355.  
  356. Getting the value of an environment variable is done by using `getenv()'.
  357.  
  358.      #include <stdlib.h>
  359.      
  360.      char *getenv(const char *name);
  361.  
  362. Setting the value of an environment variable is done by using `putenv()'.
  363.  
  364.      #include <stdlib.h>
  365.      
  366.      int putenv(char *string);
  367.  
  368. The string passed to putenv must *not* be freed or made invalid, since a
  369. pointer to it is kept by `putenv()'.  This means that it must either be a
  370. static buffer or allocated off the heap.  The string can be freed if the
  371. environment variable is redefined or deleted via another call to `putenv()'.
  372.  
  373. Remember that environment variables are inherited; each process has a
  374. separate copy of the environment. As a result, you can't change the value
  375. of an environment variable in another process, such as the shell.
  376.  
  377. Suppose you wanted to get the value for the `TERM' environment variable.
  378. You would use this code:
  379.  
  380.      char *envvar;
  381.      
  382.      envvar=getenv("TERM");
  383.      
  384.      printf("The value for the environment variable TERM is ");
  385.      if(envvar)
  386.      {
  387.          printf("%s\n",envvar);
  388.      }
  389.      else
  390.      {
  391.          printf("not set.\n");
  392.      }
  393.  
  394. Now suppose you wanted to create a new environment variable called `MYVAR',
  395. with a value of `MYVAL'.  This is how you'd do it.
  396.  
  397.      static char envbuf[256];
  398.      
  399.      sprintf(envbuf,"MYVAR=%s","MYVAL");
  400.      
  401.      if(putenv(envbuf))
  402.      {
  403.          printf("Sorry, putenv() couldn't find the memory for %s\n",envbuf);
  404.          /* Might exit() or something here if you can't live without it */
  405.      }
  406.  
  407. 1.2.2 How can I read the whole environment?
  408. -------------------------------------------
  409.  
  410. If you don't know the names of the environment variables, then the
  411. `getenv()' function isn't much use. In this case, you have to dig deeper
  412. into how the environment is stored.
  413.  
  414. A global variable, `environ', holds a pointer to an array of pointers to
  415. environment strings, each string in the form `"NAME=value"'. A `NULL'
  416. pointer is used to mark the end of the array. Here's a trivial program to
  417. print the current environment (like `printenv'):
  418.  
  419.      #include <stdio.h>
  420.      
  421.      extern char **environ;
  422.      
  423.      int main()
  424.      {
  425.          char **ep = environ;
  426.          char *p;
  427.          while ((p = *ep++))
  428.              printf("%s\n", p);
  429.          return 0;
  430.      }
  431.  
  432. In general, the `environ' variable is also passed as the third, optional,
  433. parameter to `main()'; that is, the above could have been written:
  434.  
  435.      #include <stdio.h>
  436.      
  437.      int main(int argc, char **argv, char **envp)
  438.      {
  439.          char *p;
  440.          while ((p = *envp++))
  441.              printf("%s\n", p);
  442.          return 0;
  443.      }
  444.  
  445. However, while pretty universally supported, this method isn't actually
  446. defined by the POSIX standards. (It's also less useful, in general.)
  447.  
  448. 1.3 How can I sleep for less than a second?
  449. ===========================================
  450.  
  451. The `sleep()' function, which is available on all Unixes, only allows for a
  452. duration specified in seconds. If you want finer granularity, then you need
  453. to look for alternatives:
  454.  
  455.    * Many systems have a function `usleep()'
  456.  
  457.    * You can use `select()' or `poll()', specifying no file descriptors to
  458.      test; a common technique is to write a `usleep()' function based on
  459.      either of these (see the comp.unix.questions FAQ for some examples)
  460.  
  461.    * If your system has itimers (most do), you can roll your own `usleep()'
  462.      using them (see the BSD sources for `usleep()' for how to do this)
  463.  
  464.    * If you have POSIX realtime, there is a `nanosleep()' function
  465.  
  466. Of the above, `select()' is probably the most portable (and strangely, it
  467. is often much more efficient than `usleep()' or an itimer-based method).
  468. However, the behaviour may be different if signals are caught while asleep;
  469. this may or may not be an issue depending on the application.
  470.  
  471. Whichever route you choose, it is important to realise that you may be
  472. constrained by the timer resolution of the system (some systems allow very
  473. short time intervals to be specified, others have a resolution of, say,
  474. 10ms and will round all timings to that). Also, as for `sleep()', the delay
  475. you specify is only a *minimum* value; after the specified period elapses,
  476. there will be an indeterminate delay before your process next gets
  477. scheduled.
  478.  
  479. 1.4 How can I get a finer-grained version of alarm()?
  480. =====================================================
  481.  
  482. Modern Unixes tend to implement alarms using the `setitimer()' function,
  483. which has a higher resolution and more options than the simple `alarm()'
  484. function. One should generally assume that `alarm()' and
  485. `setitimer(ITIMER_REAL)' may be the same underlying timer, and accessing it
  486. both ways may cause confusion.
  487.  
  488. Itimers can be used to implement either one-shot or repeating signals;
  489. also, there are generally 3 separate timers available:
  490.  
  491. `ITIMER_REAL'
  492.      counts real (wall clock) time, and sends the `SIGALRM' signal
  493.  
  494. `ITIMER_VIRTUAL'
  495.      counts process virtual (user CPU) time, and sends the `SIGVTALRM'
  496.      signal
  497.  
  498. `ITIMER_PROF'
  499.      counts user and system CPU time, and sends the `SIGPROF' signal; it is
  500.      intended for interpreters to use for profiling.
  501.  
  502. Itimers, however, are not part of many of the standards, despite having
  503. been present since 4.2BSD. The POSIX realtime extensions define some
  504. similar, but different, functions.
  505.  
  506. 1.5 How can a parent and child process communicate?
  507. ===================================================
  508.  
  509. A parent and child can communicate through any of the normal inter-process
  510. communication schemes (pipes, sockets, message queues, shared memory), but
  511. also have some special ways to communicate that take advantage of their
  512. relationship as a parent and child.
  513.  
  514. One of the most obvious is that the parent can get the exit status of the
  515. child.
  516.  
  517. Since the child inherits file descriptors from its parent, the parent can
  518. open both ends of a pipe, fork, then the parent close one end and the child
  519. close the other end of the pipe.  This is what happens when you call the
  520. `popen()' routine to run another program from within yours, i.e. you can
  521. write to the file descriptor returned from `popen()' and the child process
  522. sees it as its stdin, or you can read from the file descriptor and see what
  523. the program wrote to its stdout. (The mode parameter to `popen()' defines
  524. which; if you want to do both, then you can do the plumbing yourself
  525. without too much difficulty.)
  526.  
  527. Also, the child process inherits memory segments mmapped anonymously (or by
  528. mmapping the special file `/dev/zero') by the parent; these shared memory
  529. segments are not accessible from unrelated processes.
  530.  
  531. 1.6 How do I get rid of zombie processes?
  532. =========================================
  533.  
  534. 1.6.1 What is a zombie?
  535. -----------------------
  536.  
  537. When a program forks and the child finishes before the parent, the kernel
  538. still keeps some of its information about the child in case the parent
  539. might need it - for example, the parent may need to check the child's exit
  540. status.  To be able to get this information, the parent calls `wait()';
  541. when this happens, the kernel can discard the information.
  542.  
  543. In the interval between the child terminating and the parent calling
  544. `wait()', the child is said to be a `zombie'.  (If you do `ps', the child
  545. will have a `Z' in its status field to indicate this.)  Even though it's
  546. not running, it's still taking up an entry in the process table.  (It
  547. consumes no other resources, but some utilities may show bogus figures for
  548. e.g. CPU usage; this is because some parts of the process table entry have
  549. been overlaid by accounting info to save space.)
  550.  
  551. This is not good, as the process table has a fixed number of entries and it
  552. is possible for the system to run out of them. Even if the system doesn't
  553. run out, there is a limit on the number of processes each user can run,
  554. which is usually smaller than the system's limit. This is one of the
  555. reasons why you should always check if `fork()' failed, by the way!
  556.  
  557. If the parent terminates without calling wait(), the child is `adopted' by
  558. `init', which handles the work necessary to cleanup after the child.  (This
  559. is a special system program with process ID 1 - it's actually the first
  560. program to run after the system boots up).
  561.  
  562. 1.6.2 How do I prevent them from occuring?
  563. ------------------------------------------
  564.  
  565. You need to ensure that your parent process calls `wait()' (or `waitpid()',
  566. `wait3()', etc.) for every child process that terminates; or, on some
  567. systems, you can instruct the system that you are uninterested in child
  568. exit states.
  569.  
  570. Another approach is to `fork()' *twice*, and have the immediate child
  571. process exit straight away. This causes the grandchild process to be
  572. orphaned, so the init process is responsible for cleaning it up. For code
  573. to do this, see the function `fork2()' in the examples section.
  574.  
  575. To ignore child exit states, you need to do the following (check your
  576. system's manpages to see if this works):
  577.  
  578.          struct sigaction sa;
  579.          sa.sa_handler = SIG_IGN;
  580.      #ifdef SA_NOCLDWAIT
  581.          sa.sa_flags = SA_NOCLDWAIT;
  582.      #else
  583.          sa.sa_flags = 0;
  584.      #endif
  585.          sigemptyset(&sa.sa_mask);
  586.          sigaction(SIGCHLD, &sa, NULL);
  587.  
  588. If this is successful, then the `wait()' functions are prevented from
  589. working; if any of them are called, they will wait until *all* child
  590. processes have terminated, then return failure with `errno == ECHILD'.
  591.  
  592. The other technique is to catch the SIGCHLD signal, and have the signal
  593. handler call `waitpid()' or `wait3()'. See the examples section for a
  594. complete program.
  595.  
  596. 1.7 How do I get my program to act like a daemon?
  597. =================================================
  598.  
  599. A "daemon" process is usually defined as a background process that does not
  600. belong to a terminal session. Many system services are performed by
  601. daemons; network services, printing etc.
  602.  
  603. Simply invoking a program in the background isn't really adequate for these
  604. long-running programs; that does not correctly detach the process from the
  605. terminal session that started it. Also, the conventional way of starting
  606. daemons is simply to issue the command manually or from an rc script; the
  607. daemon is expected to put *itself* into the background.
  608.  
  609. Here are the steps to become a daemon:
  610.  
  611.   1. `fork()' so the parent can exit, this returns control to the command
  612.      line or shell invoking your program.  This step is required so that
  613.      the new process is guaranteed not to be a process group leader. The
  614.      next step, `setsid()', fails if you're a process group leader.
  615.  
  616.   2. `setsid()' to become a process group and session group leader. Since a
  617.      controlling terminal is associated with a session, and this new
  618.      session has not yet acquired a controlling terminal our process now
  619.      has no controlling terminal, which is a Good Thing for daemons.
  620.  
  621.   3. `fork()' again so the parent, (the session group leader), can exit.
  622.      This means that we, as a non-session group leader, can never regain a
  623.      controlling terminal.
  624.  
  625.   4. `chdir("/")' to ensure that our process doesn't keep any directory in
  626.      use. Failure to do this could make it so that an administrator
  627.      couldn't unmount a filesystem, because it was our current directory.
  628.  
  629.      [Equivalently, we could change to any directory containing files
  630.      important to the daemon's operation.]
  631.  
  632.   5. `umask(0)' so that we have complete control over the permissions of
  633.      anything we write. We don't know what umask we may have inherited.
  634.  
  635.      [This step is optional]
  636.  
  637.   6. `close()' fds 0, 1, and 2. This releases the standard in, out, and
  638.      error we inherited from our parent process. We have no way of knowing
  639.      where these fds might have been redirected to. Note that many daemons
  640.      use `sysconf()' to determine the limit `_SC_OPEN_MAX'.  `_SC_OPEN_MAX'
  641.      tells you the maximun open files/process. Then in a loop, the daemon
  642.      can close all possible file descriptors. You have to decide if you
  643.      need to do this or not.  If you think that there might be
  644.      file-descriptors open you should close them, since there's a limit on
  645.      number of concurrent file descriptors.
  646.  
  647.   7. Establish new open descriptors for stdin, stdout and stderr. Even if
  648.      you don't plan to use them, it is still a good idea to have them open.
  649.      The precise handling of these is a matter of taste; if you have a
  650.      logfile, for example, you might wish to open it as stdout or stderr,
  651.      and open `/dev/null' as stdin; alternatively, you could open
  652.      `/dev/console' as stderr and/or stdout, and `/dev/null' as stdin, or
  653.      any other combination that makes sense for your particular daemon.
  654.  
  655. Almost none of this is necessary (or advisable) if your daemon is being
  656. started by `inetd'.  In that case, stdin, stdout and stderr are all set up
  657. for you to refer to the network connection, and the `fork()'s and session
  658. manipulation should *not* be done (to avoid confusing `inetd').  Only the
  659. `chdir()' and `umask()' steps remain as useful.
  660.  
  661. 1.8 How can I look at process in the system like ps does?
  662. =========================================================
  663.  
  664. You really *don't* want to do this.
  665.  
  666. The most portable way, by far, is to do `popen(pscmd, "r")' and parse the
  667. output. (pscmd should be something like `"ps -ef"' on SysV systems; on BSD
  668. systems there are many possible display options: choose one.)
  669.  
  670. In the examples section, there are two complete versions of this; one for
  671. SunOS 4, which requires root permission to run and uses the `kvm_*'
  672. routines to read the information from kernel data structures; and another
  673. for SVR4 systems (including SunOS 5), which uses the `/proc' filesystem.
  674.  
  675. It's even easier on systems with an SVR4.2-style `/proc'; just read a
  676. psinfo_t structure from the file `/proc/PID/psinfo' for each PID of
  677. interest. However, this method, while probably the cleanest, is also
  678. perhaps the least well-supported. (On FreeBSD's `/proc', you read a
  679. semi-undocumented printable string from `/proc/PID/status'; Linux has
  680. something similar.)
  681.  
  682. 1.9 Given a pid, how can I tell if it's a running program?
  683. ==========================================================
  684.  
  685. Use `kill()' with 0 for the signal number.
  686.  
  687. There are four possible results from this call:
  688.  
  689.    * `kill()' returns 0
  690.  
  691.         - this implies that a process exists with the given PID, and the
  692.           system would allow you to send signals to it. It is
  693.           system-dependent whether the process could be a zombie.
  694.  
  695.    * `kill()' returns -1, `errno == ESRCH'
  696.  
  697.         - either no process exists with the given PID, or security
  698.           enhancements are causing the system to deny its existence. (On
  699.           some systems, the process could be a zombie.)
  700.  
  701.    * `kill()' returns -1, `errno == EPERM'
  702.  
  703.         - the system would not allow you to kill the specified process.
  704.           This means that either the process exists (again, it could be a
  705.           zombie) or draconian security enhancements are present (e.g. your
  706.           process is not allowed to send signals to *anybody*).
  707.  
  708.    * `kill()' returns -1, with some other value of `errno'
  709.  
  710.         - you are in trouble!
  711.  
  712. The most-used technique is to assume that success or failure with `EPERM'
  713. implies that the process exists, and any other error implies that it
  714. doesn't.
  715.  
  716. An alternative exists, if you are writing specifically for a system (or all
  717. those systems) that provide a `/proc' filesystem: checking for the
  718. existence of `/proc/PID' may work.
  719.  
  720. 1.10 What's the return value of system/pclose/waitpid?
  721. ======================================================
  722.  
  723.      The return value of `system()', `pclose()', or `waitpid()' doesn't
  724.      seem to be the exit value of my process...  or the exit value is
  725.      shifted left 8 bits... what's the deal?
  726.  
  727. The man page is right, and so are you!  If you read the man page for
  728. `waitpid()' you'll find that the return code for the process is encoded.
  729. The value returned by the process is normally in the top 16 bits, and the
  730. rest is used for other things.  You can't rely on this though, not if you
  731. want to be portable, so the suggestion is that you use the macros provided.
  732. These are usually documented under `wait()' or `wstat'.
  733.  
  734. Macros defined for the purpose (in `<sys/wait.h>') include (stat is the
  735. value returned by `waitpid()'):
  736.  
  737. `WIFEXITED(stat)'
  738.      Non zero if child exited normally.
  739.  
  740. `WEXITSTATUS(stat)'
  741.      exit code returned by child
  742.  
  743. `WIFSIGNALED(stat)'
  744.      Non-zero if child was terminated by a signal
  745.  
  746. `WTERMSIG(stat)'
  747.      signal number that terminated child
  748.  
  749. `WIFSTOPPED(stat)'
  750.      non-zero if child is stopped
  751.  
  752. `WSTOPSIG(stat)'
  753.      number of signal that stopped child
  754.  
  755. `WIFCONTINUED(stat)'
  756.      non-zero if status was for continued child
  757.  
  758. `WCOREDUMP(stat)'
  759.      If `WIFSIGNALED(stat)' is non-zero, this is non-zero if the process
  760.      left behind a core dump.
  761.  
  762. 1.11 How do I find out about a process' memory usage?
  763. =====================================================
  764.  
  765. Look at `getrusage()', if available.
  766.  
  767. 1.12 Why do processes never decrease in size?
  768. =============================================
  769.  
  770. When you free memory back to the heap with `free()', on almost all systems
  771. that *doesn't* reduce the memory usage of your program.  The memory
  772. `free()'d is still part of the process' address space, and will be used to
  773. satisfy future `malloc()' requests.
  774.  
  775. If you really need to free memory back to the system, look at using
  776. `mmap()' to allocate private anonymous mappings.  When these are unmapped,
  777. the memory really is released back to the system.  Certain implementations
  778. of `malloc()' (e.g. in the GNU C Library) automatically use `mmap()' where
  779. available to perform large allocations; these blocks are then returned to
  780. the system on `free()'.
  781.  
  782. Of course, if your program increases in size when you think it shouldn't,
  783. you may have a `memory leak' - a bug in your program that results in unused
  784. memory not being freed.
  785.  
  786. 1.13 How do I change the name of my program (as seen by `ps')?
  787. ==============================================================
  788.  
  789. On BSDish systems, the `ps' program actually looks into the address space
  790. of the running process to find the current `argv[]', and displays that.
  791. That enables a program to change its `name' simply by modifying `argv[]'.
  792.  
  793. On SysVish systems, the command name and usually the first 80 bytes of the
  794. parameters are stored in the process' u-area, and so can't be directly
  795. modified. There may be a system call to change this (unlikely), but
  796. otherwise the only way is to perform an `exec()', or write into kernel
  797. memory (dangerous, and only possible if running as root).
  798.  
  799. Some systems (notably Solaris) may have two separate versions of `ps', one
  800. in `/usr/bin/ps' with SysV behaviour, and one in `/usr/ucb/ps' with BSD
  801. behaviour. On these systems, if you change `argv[]', then the BSD version
  802. of `ps' will reflect the change, and the SysV version won't.
  803.  
  804. Check to see if your system has a function `setproctitle()'.
  805.  
  806. 1.14 How can I find a process' executable file?
  807. ===============================================
  808.  
  809. This would be a good candidate for a list of `Frequently Unanswered
  810. Questions', because the fact of asking the question usually means that the
  811. design of the program is flawed. :-)
  812.  
  813. You can make a `best guess' by looking at the value of `argv[0]'.  If this
  814. contains a `/', then it is probably the absolute or relative (to the
  815. current directory at program start) path of the executable.  If it does
  816. not, then you can mimic the shell's search of the `PATH' variable, looking
  817. for the program.  However, success is not guaranteed, since it is possible
  818. to invoke programs with arbitrary values of `argv[0]', and in any case the
  819. executable may have been renamed or deleted since it was started.
  820.  
  821. If all you want is to be able to print an appropriate invocation name with
  822. error messages, then the best approach is to have `main()' save the value
  823. of `argv[0]' in a global variable for use by the entire program.  While
  824. there is no guarantee whatsoever that the value in `argv[0]' will be
  825. meaningful, it is the best option available in most circumstances.
  826.  
  827. The most common reason people ask this question is in order to locate
  828. configuration files with their program. This is considered to be bad form;
  829. directories containing executables should contain *nothing* except
  830. executables, and administrative requirements often make it desirable for
  831. configuration files to be located on different filesystems to executables.
  832.  
  833. A less common, but more legitimate, reason to do this is to allow the
  834. program to call `exec()' *on itself*; this is a method used (e.g. by some
  835. versions of `sendmail') to completely reinitialise the process (e.g. if a
  836. daemon receives a `SIGHUP').
  837.  
  838. 1.14.1 So where do I put my configuration files then?
  839. -----------------------------------------------------
  840.  
  841. The correct directory for this usually depends on the particular flavour of
  842. Unix you're using; `/var/opt/PACKAGE', `/usr/local/lib', `/usr/local/etc',
  843. or any of several other possibilities.  User-specific configuration files
  844. are usually hidden `dotfiles' under `$HOME' (e.g. `$HOME/.exrc').
  845.  
  846. From the point of view of a package that is expected to be usable across a
  847. range of systems, this usually implies that the location of any sitewide
  848. configuration files will be a compiled-in default, possibly using a
  849. `--prefix' option on a configure script (Autoconf scripts do this).  You
  850. might wish to allow this to be overridden at runtime by an environment
  851. variable.  (If you're not using a configure script, then put the default in
  852. the Makefile as a `-D' option on compiles, or put it in a `config.h' header
  853. file, or something similar.)
  854.  
  855. User-specific configuration should be either a single dotfile under
  856. `$HOME', or, if you need multiple files, a dot-subdirectory.  (Files or
  857. directories whose names start with a dot are omitted from directory
  858. listings by default.) Avoid creating multiple entries under `$HOME',
  859. because this can get very cluttered. Again, you can allow the user to
  860. override this location with an environment variable. Programs should always
  861. behave sensibly if they fail to find any per-user configuration.
  862.  
  863. 1.15 Why doesn't my process get SIGHUP when its parent dies?
  864. ============================================================
  865.  
  866. Because it's not supposed to.
  867.  
  868. `SIGHUP' is a signal that means, by convention, "the terminal line got hung
  869. up".  It has nothing to do with parent processes, and is usually generated
  870. by the tty driver (and delivered to the foreground process group).
  871.  
  872. However, as part of the session management system, there are exactly two
  873. cases where `SIGHUP' is sent on the death of a process:
  874.  
  875.    * When the process that dies is the session leader of a session that is
  876.      attached to a terminal device, `SIGHUP' is sent to all processes in
  877.      the foreground process group of that terminal device.
  878.  
  879.    * When the death of a process causes a process group to become orphaned,
  880.      and one or more processes in the orphaned group are *stopped*, then
  881.      `SIGHUP' and `SIGCONT' are sent to all members of the orphaned group.
  882.      (An orphaned process group is one where no process in the group has a
  883.      parent which is part of the same session, but not the same process
  884.      group.)
  885.  
  886. 1.16 How can I kill all descendents of a process?
  887. =================================================
  888.  
  889. There isn't a fully general approach to doing this.  While you can
  890. determine the relationships between processes by parsing `ps' output, this
  891. is unreliable in that it represents only a snapshot of the system.
  892.  
  893. However, if you're lauching a subprocess that might spawn further
  894. subprocesses of its own, and you want to be able to kill the entire spawned
  895. job at one go, the solution is to put the subprocess into a new process
  896. group, and kill that process group if you need to.
  897.  
  898. The preferred function for creating process groups is `setpgid()'.  Use
  899. this if possible rather than `setpgrp()' because the latter differs between
  900. systems (on some systems `setpgrp();' is equivalent to `setpgid(0,0);', on
  901. others, `setpgrp()' and `setpgid()' are identical).
  902.  
  903. See the job-control example in the examples section.
  904.  
  905. Putting a subprocess into its own process group has a number of effects.
  906. In particular, unless you explicitly place the new process group in the
  907. foreground, it will be treated as a background job with these consequences:
  908.  
  909.    * it will be stopped with `SIGTTIN' if it attempts to read from the
  910.      terminal
  911.  
  912.    * if `tostop' is set in the terminal modes, it will be stopped with
  913.      `SIGTTOU' if it attempts to write to the terminal (attempting to
  914.      change the terminal modes should also cause this, independently of the
  915.      current setting of `tostop')
  916.  
  917.    * The subprocess will not receive keyboard signals from the terminal
  918.      (e.g. `SIGINT' or `SIGQUIT')
  919.  
  920. In many applications input and output will be redirected anyway, so the
  921. most significant effect will be the lack of keyboard signals. The parent
  922. application should arrange to catch at least `SIGINT' and `SIGQUIT' (and
  923. preferably `SIGTERM' as well) and clean up any background jobs as necessary.
  924.  
  925. 2. General File handling (including pipes and sockets)
  926. ******************************************************
  927.  
  928. See also the Sockets FAQ, available at:
  929.  
  930. `http://www.lcg.org/sock-faq/'
  931.  
  932. 2.1 How to manage multiple connections?
  933. =======================================
  934.  
  935.      I have to monitor more than one (fd/connection/stream) at a time. How
  936.      do I manage all of them?
  937.  
  938. Use `select()' or `poll()'.
  939.  
  940. Note: `select()' was introduced in BSD, whereas `poll()' is an artifact of
  941. SysV STREAMS. As such, there are portability issues; pure BSD systems may
  942. still lack `poll()', whereas some older SVR3 systems may not have
  943. `select()'. SVR4 added `select()', and the Posix.1g standard defines both.
  944.  
  945. `select()' and `poll()' essentially do the same thing, just differently.
  946. Both of them examine a set of file descriptors to see if specific events
  947. are pending on any, and then optionally wait for a specified time for an
  948. event to happen.
  949.  
  950. [Important note: neither `select()' nor `poll()' do anything useful when
  951. applied to plain files; they are useful for sockets, pipes, ptys, ttys &
  952. possibly other character devices, but this is system-dependent.]
  953.  
  954. There the similarity ends....
  955.  
  956. 2.1.1 How do I use select()?
  957. ----------------------------
  958.  
  959. The interface to `select()' is primarily based on the concept of an
  960. `fd_set', which is a set of FDs (usually implemented as a bit-vector). In
  961. times past, it was common to assume that FDs were smaller than 32, and just
  962. use an int to store the set, but these days, one usually has more FDs
  963. available, so it is important to use the standard macros for manipulating
  964. fd_sets:
  965.  
  966.      fd_set set;
  967.      FD_ZERO(&set);      /* empties the set */
  968.      FD_SET(fd,&set);    /* adds FD to the set */
  969.      FD_CLR(fd,&set);    /* removes FD from the set */
  970.      FD_ISSET(fd,&set)   /* true if FD is in the set */
  971.  
  972. In most cases, it is the system's responsibility to ensure that fdsets can
  973. handle the whole range of file descriptors, but in some cases you may have
  974. to predefine the `FD_SETSIZE' macro.  *This is system-dependent*; check
  975. your `select()' manpage. Also, some systems have problems handling more
  976. than 1024 file descriptors in `select()'.
  977.  
  978. The basic interface to select is simple:
  979.  
  980.      int select(int nfds, fd_set *readset,
  981.                           fd_set *writeset,
  982.                           fd_set *exceptset, struct timeval *timeout);
  983.  
  984. where
  985.  
  986. `nfds'
  987.      the number of FDs to examine; this must be greater than the largest FD
  988.      in any of the fdsets, *not* the actual number of FDs specified
  989.  
  990. `readset'
  991.      the set of FDs to examine for readability
  992.  
  993. `writeset'
  994.      the set of FDs to examine for writability
  995.  
  996. `exceptfds'
  997.      the set of FDs to examine for exceptional status (note: errors are
  998.      *not* exceptional statuses)
  999.  
  1000. `timeout'
  1001.      NULL for infinite timeout, or points to a timeval specifying the
  1002.      maximum wait time (if `tv_sec' and `tv_usec' both equal zero, then the
  1003.      status of the FDs is polled, but the call never blocks)
  1004.  
  1005. The call returns the number of `ready' FDs found, and the three fdsets are
  1006. modified in-place, with only the ready FDs left in the sets. Use the
  1007. `FD_ISSET' macro to test the returned sets.
  1008.  
  1009. Here's a simple example of testing a single FD for readability:
  1010.  
  1011.      int isready(int fd)
  1012.      {
  1013.          int rc;
  1014.          fd_set fds;
  1015.          struct timeval tv;
  1016.      
  1017.          FD_ZERO(&fds);
  1018.          FD_SET(fd,&fds);
  1019.          tv.tv_sec = tv.tv_usec = 0;
  1020.      
  1021.          rc = select(fd+1, &fds, NULL, NULL, &tv);
  1022.          if (rc < 0)
  1023.            return -1;
  1024.      
  1025.          return FD_ISSET(fd,&fds) ? 1 : 0;
  1026.      }
  1027.  
  1028. Note that we can pass `NULL' for fdsets that we aren't interested in
  1029. testing.
  1030.  
  1031. 2.1.2 How do I use poll()?
  1032. --------------------------
  1033.  
  1034. `poll()' accepts a pointer to a list of `struct pollfd', in which the
  1035. descriptors and the events you wish to poll for are stored.  The events are
  1036. specified via a bitwise mask in the events field of the structure.  The
  1037. instance of the structure will later be filled in and returned to you with
  1038. any events which occured.  Macros defined by `poll.h' on SVR4 (probably
  1039. older versions as well), are used to specify the events in the field.  A
  1040. timeout may be specified in milliseconds, only the type provided is an
  1041. integer which is quite perplexing.  A timeout of 0 causes `poll()' to
  1042. return immediately; a value of -1 will suspend poll until an event is found
  1043. to be true.
  1044.  
  1045.      struct pollfd {
  1046.          int fd;        /* The descriptor. */
  1047.          short events;  /* The event(s) is/are specified here. */
  1048.          short revents; /* Events found are returned here. */
  1049.      };
  1050.  
  1051. A lot like `select()', the return value if positive reflects how many
  1052. descriptors were found to satisfy the events requested.  A zero return
  1053. value is returned if the timeout period is reached before any of the events
  1054. specified have occured.  A negative value should immediately be followed by
  1055. a check of `errno', since it signifies an error.
  1056.  
  1057. If no events are found, `revents' is cleared, so there's no need for you to
  1058. do this yourself.
  1059.  
  1060. The returned events are tested to contain the event.
  1061.  
  1062. Here's an example:
  1063.  
  1064.      /* Poll on two descriptors for Normal data, or High priority data.
  1065.         If any found call function handle() with appropriate descriptor
  1066.         and priority. Don't timeout, only give up if error, or one of the
  1067.         descriptors hangs up. */
  1068.      
  1069.      #include <stdlib.h>
  1070.      #include <stdio.h>
  1071.      
  1072.      #include <sys/types.h>
  1073.      #include <stropts.h>
  1074.      #include <poll.h>
  1075.      
  1076.      #include <unistd.h>
  1077.      #include <errno.h>
  1078.      #include <string.h>
  1079.      
  1080.      #define NORMAL_DATA 1
  1081.      #define HIPRI_DATA 2
  1082.      
  1083.      int poll_two_normal(int fd1,int fd2)
  1084.      {
  1085.          struct pollfd poll_list[2];
  1086.          int retval;
  1087.      
  1088.          poll_list[0].fd = fd1;
  1089.          poll_list[1].fd = fd2;
  1090.          poll_list[0].events = POLLIN|POLLPRI;
  1091.          poll_list[1].events = POLLIN|POLLPRI;
  1092.      
  1093.          while(1)
  1094.          {
  1095.              retval = poll(poll_list,(unsigned long)2,-1);
  1096.              /* Retval will always be greater than 0 or -1 in this case.
  1097.                 Since we're doing it while blocking */
  1098.      
  1099.              if(retval < 0)
  1100.              {
  1101.                  fprintf(stderr,"Error while polling: %s\n",strerror(errno));
  1102.                  return -1;
  1103.              }
  1104.      
  1105.              if(((poll_list[0].revents&POLLHUP) == POLLHUP) ||
  1106.                 ((poll_list[0].revents&POLLERR) == POLLERR) ||
  1107.                 ((poll_list[0].revents&POLLNVAL) == POLLNVAL) ||
  1108.                 ((poll_list[1].revents&POLLHUP) == POLLHUP) ||
  1109.                 ((poll_list[1].revents&POLLERR) == POLLERR) ||
  1110.                 ((poll_list[1].revents&POLLNVAL) == POLLNVAL))
  1111.                return 0;
  1112.      
  1113.              if((poll_list[0].revents&POLLIN) == POLLIN)
  1114.                handle(poll_list[0].fd,NORMAL_DATA);
  1115.              if((poll_list[0].revents&POLLPRI) == POLLPRI)
  1116.                handle(poll_list[0].fd,HIPRI_DATA);
  1117.              if((poll_list[1].revents&POLLIN) == POLLIN)
  1118.                handle(poll_list[1].fd,NORMAL_DATA);
  1119.              if((poll_list[1].revents&POLLPRI) == POLLPRI)
  1120.                handle(poll_list[1].fd,HIPRI_DATA);
  1121.          }
  1122.      }
  1123.  
  1124. 2.1.3 Can I use SysV IPC at the same time as select or poll?
  1125. ------------------------------------------------------------
  1126.  
  1127. *No.* (Except on AIX, which has an incredibly ugly kluge to allow this.)
  1128.  
  1129. In general, trying to combine the use of `select()' or `poll()' with using
  1130. SysV message queues is troublesome. SysV IPC objects are not handled by
  1131. file descriptors, so they can't be passed to `select()' or `poll()'. There
  1132. are a number of workarounds, of varying degrees of ugliness:
  1133.  
  1134.    - Abandon SysV IPC completely. :-)
  1135.  
  1136.    - `fork()', and have the child process handle the SysV IPC,
  1137.      communicating with the parent process by a pipe or socket, which the
  1138.      parent process can `select()' on.
  1139.  
  1140.    - As above, but have the child process do the `select()', and
  1141.      communicate with the parent by message queue.
  1142.  
  1143.    - Arrange for the process that sends messages to you to send a signal
  1144.      after each message. *Warning:* handling this right is non-trivial;
  1145.      it's very easy to write code that can potentially lose messages or
  1146.      deadlock using this method.
  1147.  
  1148. (Other methods exist.)
  1149.  
  1150. 2.2 How can I tell when the other end of a connection shuts down?
  1151. =================================================================
  1152.  
  1153. If you try to read from a pipe, socket, FIFO etc. when the writing end of
  1154. the connection has been closed, you get an end-of-file indication (`read()'
  1155. returns 0 bytes read). If you try and write to a pipe, socket etc. when the
  1156. reading end has closed, then a `SIGPIPE' signal will be delivered to the
  1157. process, killing it unless the signal is caught. (If you ignore or block
  1158. the signal, the `write()' call fails with `EPIPE'.)
  1159.  
  1160. 2.3 Best way to read directories?
  1161. =================================
  1162.  
  1163. While historically there have been several different interfaces for this,
  1164. the only one that really matters these days the the Posix.1 standard
  1165. `<dirent.h>' functions.
  1166.  
  1167. The function `opendir()' opens a specified directory; `readdir()' reads
  1168. directory entries from it in a standardised format; `closedir()' does the
  1169. obvious. Also provided are `rewinddir()', `telldir()' and `seekdir()' which
  1170. should also be obvious.
  1171.  
  1172. If you are looking to expand a wildcard filename, then most systems have
  1173. the `glob()' function; also check out `fnmatch()' to match filenames
  1174. against a wildcard, or `ftw()' to traverse entire directory trees.
  1175.  
  1176. 2.4 How can I find out if someone else has a file open?
  1177. =======================================================
  1178.  
  1179. This is another candidate for `Frequently Unanswered Questions' because, in
  1180. general, your program should never be interested in whether someone else
  1181. has the file open.  If you need to deal with concurrent access to the file,
  1182. then you should be looking at advisory locking.
  1183.  
  1184. This is, in general, too hard to do anyway. Tools like `fuser' and `lsof'
  1185. that find out about open files do so by grovelling through kernel data
  1186. structures in a most unhealthy fashion. You can't usefully invoke them from
  1187. a program, either, because by the time you've found out that the file
  1188. is/isn't open, the information may already be out of date.
  1189.  
  1190. 2.5 How do I `lock' a file?
  1191. ===========================
  1192.  
  1193. There are three main file locking mechanisms available. All of them are
  1194. `advisory'[*], which means that they rely on programs co-operating in order
  1195. to work.  It is therefore vital that all programs in an application should
  1196. be consistent in their locking regime, and great care is required when your
  1197. programs may be sharing files with third-party software.
  1198.  
  1199. [*] Well, actually some Unices permit mandatory locking via the sgid bit -
  1200. RTFM for this hack.
  1201.  
  1202. Some applications use lock files - something like `FILENAME.lock'.  Simply
  1203. testing for the existence of such files is inadequate though, since a
  1204. process may have been killed while holding the lock.  The method used by
  1205. UUCP (probably the most notable example: it uses lock files for controlling
  1206. access to modems, remote systems etc.) is to store the PID in the lockfile,
  1207. and test if that pid is still running.  Even this isn't enough to be sure
  1208. (since PIDs are recycled); it has to have a backstop check to see if the
  1209. lockfile is old, which means that the process holding the lock must update
  1210. the file regularly.  Messy.
  1211.  
  1212. The locking functions are:
  1213.  
  1214.          flock();
  1215.          lockf();
  1216.          fcntl();
  1217.  
  1218. `flock()' originates with BSD, and is now available in most (but not all)
  1219. Unices.  It is simple and effective on a single host, but doesn't work at
  1220. all with NFS.  It locks an entire file. Perhaps rather deceptively, the
  1221. popular Perl programming language implements its own `flock()' where
  1222. necessary, conveying the illusion of true portability.
  1223.  
  1224. `fcntl()' is the only POSIX-compliant locking mechanism, and is therefore
  1225. the only truly portable lock.  It is also the most powerful, and the
  1226. hardest to use.  For NFS-mounted file systems, `fcntl()' requests are
  1227. passed to a daemon (`rpc.lockd'), which communicates with the lockd on the
  1228. server host.  Unlike `flock()' it is capable of record-level locking.
  1229.  
  1230. `lockf()' is merely a simplified programming interface to the locking
  1231. functions of `fcntl()'.
  1232.  
  1233. Whatever locking mechanism you use, it is important to sync all your file
  1234. IO while the lock is active:
  1235.  
  1236.          lock(fd);
  1237.          write_to(some_function_of(fd));
  1238.          flush_output_to(fd); /* NEVER unlock while output may be buffered */
  1239.          unlock(fd);
  1240.          do_something_else;   /* another process might update it */
  1241.          lock(fd);
  1242.          seek(fd, somewhere); /* because our old file pointer is not safe */
  1243.          do_something_with(fd);
  1244.          ...
  1245.  
  1246. A few useful `fcntl()' locking recipes (error handling omitted for
  1247. simplicity) are:
  1248.  
  1249.      #include <fcntl.h>
  1250.      #include <unistd.h>
  1251.      
  1252.      read_lock(int fd)   /* a shared lock on an entire file */
  1253.      {
  1254.          fcntl(fd, F_SETLKW, file_lock(F_RDLCK, SEEK_SET));
  1255.      }
  1256.      
  1257.      write_lock(int fd)  /* an exclusive lock on an entire file */
  1258.      {
  1259.          fcntl(fd, F_SETLKW, file_lock(F_WRLCK, SEEK_SET));
  1260.      }
  1261.      
  1262.      append_lock(int fd) /* a lock on the _end_ of a file -- other
  1263.                             processes may access existing records */
  1264.      {
  1265.          fcntl(fd, F_SETLKW, file_lock(F_WRLCK, SEEK_END));
  1266.      }
  1267.  
  1268. The function file_lock used by the above is
  1269.  
  1270.      struct flock* file_lock(short type, short whence)
  1271.      {
  1272.          static struct flock ret ;
  1273.          ret.l_type = type ;
  1274.          ret.l_start = 0 ;
  1275.          ret.l_whence = whence ;
  1276.          ret.l_len = 0 ;
  1277.          ret.l_pid = getpid() ;
  1278.          return &ret ;
  1279.      }
  1280.  
  1281. 2.6 How do I find out if a file has been updated by another process?
  1282. ====================================================================
  1283.  
  1284. This is close to being a Frequently Unanswered Question, because people
  1285. asking it are often looking for some notification from the system when a
  1286. file or directory is changed, and there is no portable way of getting this.
  1287. (IRIX has a non-standard facility for monitoring file accesses, but I've
  1288. never heard of it being available in any other flavour.)
  1289.  
  1290. In general, the best you can do is to use `fstat()' on the file. (Note: the
  1291. overhead on `fstat()' is quite low, usually much lower than the overhead of
  1292. `stat()'.) By watching the mtime and ctime of the file, you can detect when
  1293. it is modified, or deleted/linked/renamed. This is a bit kludgy, so you
  1294. might want to rethink *why* you want to do it.
  1295.  
  1296. 2.7 How does the `du' utility work?
  1297. ===================================
  1298.  
  1299. `du' simply traverses the directory structure calling `stat()' (or more
  1300. accurately, `lstat()') on every file and directory it encounters, adding up
  1301. the number of blocks consumed by each.
  1302.  
  1303. If you want more detail about how it works, then the simple answer is:
  1304.  
  1305.      Use the source, Luke!
  1306.  
  1307. Source for BSD systems (FreeBSD, NetBSD and OpenBSD) is available as
  1308. unpacked source trees on their FTP distribution sites; source for GNU
  1309. versions of utilities is available from any of the GNU mirrors, but you
  1310. have to unpack the archives yourself.
  1311.  
  1312. 2.8 How do I find the size of a file?
  1313. =====================================
  1314.  
  1315. Use `stat()', or `fstat()' if you have the file open.
  1316.  
  1317. These calls fill in a data structure containing all the information about
  1318. the file that the system keeps track of; that includes the owner, group,
  1319. permissions, size, last access time, last modification time, etc.
  1320.  
  1321. The following routine illustrates how to use `stat()' to get the file size.
  1322.  
  1323.      #include <stdlib.h>
  1324.      #include <stdio.h>
  1325.      
  1326.      #include <sys/types.h>
  1327.      #include <sys/stat.h>
  1328.      
  1329.      int get_file_size(char *path,off_t *size)
  1330.      {
  1331.        struct stat file_stats;
  1332.      
  1333.        if(stat(path,&file_stats))
  1334.          return -1;
  1335.      
  1336.        *size = file_stats.st_size;
  1337.        return 0;
  1338.      }
  1339.  
  1340. 2.9 How do I expand `~' in a filename like the shell does?
  1341. ==========================================================
  1342.  
  1343. The standard interpretation for `~' at the start of a filename is: if alone
  1344. or followed by a `/', then substitute the current user's home directory; if
  1345. followed by the name of a user, then substitute that user's home directory.
  1346. If no valid expansion can be found, then shells will leave the filename
  1347. unchanged.
  1348.  
  1349. Be wary, however, of filenames that actually start with the `~' character.
  1350. Indiscriminate tilde-expansion can make it very difficult to specify such
  1351. filenames to a program; while quoting will prevent the shell from doing the
  1352. expansion, the quotes will have been removed by the time the program sees
  1353. the filename. As a general rule, do not try and perform tilde-expansion on
  1354. filenames that have been passed to the program on the command line or in
  1355. environment variables. (Filenames generated within the program, obtained by
  1356. prompting the user, or obtained from a configuration file, are good
  1357. candidates for tilde-expansion.)
  1358.  
  1359. Here's a piece of C++ code (using the standard string class) to do the job:
  1360.  
  1361.      string expand_path(const string& path)
  1362.      {
  1363.          if (path.length() == 0 || path[0] != '~')
  1364.            return path;
  1365.      
  1366.          const char *pfx = NULL;
  1367.          string::size_type pos = path.find_first_of('/');
  1368.      
  1369.          if (path.length() == 1 || pos == 1)
  1370.          {
  1371.              pfx = getenv("HOME");
  1372.              if (!pfx)
  1373.              {
  1374.                  // Punt. We're trying to expand ~/, but HOME isn't set
  1375.                  struct passwd *pw = getpwuid(getuid());
  1376.                  if (pw)
  1377.                    pfx = pw->pw_dir;
  1378.              }
  1379.          }
  1380.          else
  1381.          {
  1382.              string user(path,1,(pos==string::npos) ? string::npos : pos-1);
  1383.              struct passwd *pw = getpwnam(user.c_str());
  1384.              if (pw)
  1385.                pfx = pw->pw_dir;
  1386.          }
  1387.      
  1388.          // if we failed to find an expansion, return the path unchanged.
  1389.      
  1390.          if (!pfx)
  1391.            return path;
  1392.      
  1393.          string result(pfx);
  1394.      
  1395.          if (pos == string::npos)
  1396.            return result;
  1397.      
  1398.          if (result.length() == 0 || result[result.length()-1] != '/')
  1399.            result += '/';
  1400.      
  1401.          result += path.substr(pos+1);
  1402.      
  1403.          return result;
  1404.      }
  1405.  
  1406. 2.10 What can I do with named pipes (FIFOs)?
  1407. ============================================
  1408.  
  1409. 2.10.1 What is a named pipe?
  1410. ----------------------------
  1411.  
  1412. A "named pipe" is a special file that is used to transfer data between
  1413. unrelated processes.  One (or more) processes write to it, while another
  1414. process reads from it.  Named pipes are visible in the file system and may
  1415. be viewed with `ls' like any other file.  (Named pipes are also called
  1416. "fifo"s; this term stands for `First In, First Out'.)
  1417.  
  1418. Named pipes may be used to pass data between unrelated processes, while
  1419. normal (unnamed) pipes can only connect parent/child processes (unless you
  1420. try *very* hard).
  1421.  
  1422. Named pipes are strictly unidirectional, even on systems where anonymous
  1423. pipes are bidirectional (full-duplex).
  1424.  
  1425. 2.10.2 How do I create a named pipe?
  1426. ------------------------------------
  1427.  
  1428. To create a named pipe interactively, you'll use either `mknod' or
  1429. `mkfifo'. On some systems, mknod will be found in /etc. In other words, it
  1430. might not be on your path. See your man pages for details.
  1431.  
  1432. To make a named pipe within a C program use `mkfifo()':
  1433.  
  1434.      /* set the umask explicitly, you don't know where it's been */
  1435.      umask(0);
  1436.      if (mkfifo("test_fifo", S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP))
  1437.      {
  1438.          perror("mkfifo");
  1439.          exit(1);
  1440.      }
  1441.  
  1442. If you don't have `mkfifo()', you'll have to use `mknod()':
  1443.  
  1444.      /* set the umask explicitly, you don't know where it's been */
  1445.      umask(0);
  1446.      if (mknod("test_fifo",
  1447.                  S_IFIFO | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP,
  1448.                 0))
  1449.      {
  1450.          perror("mknod");
  1451.          exit(1);
  1452.      }
  1453.  
  1454. 2.10.3 How do I use a named pipe?
  1455. ---------------------------------
  1456.  
  1457. To use the pipe, you open it like a normal file, and use `read()' and
  1458. `write()' just as though it was a plain pipe.
  1459.  
  1460. However, the `open()' of the pipe may block. The following rules apply:
  1461.  
  1462.    * If you open for both reading and writing (`O_RDWR'), then the open
  1463.      will not block.
  1464.  
  1465.    * If you open for reading (`O_RDONLY'), the open will block until
  1466.      another process opens the FIFO for writing, unless `O_NONBLOCK' is
  1467.      specified, in which case the open succeeds.
  1468.  
  1469.    * If you open for writing `O_WRONLY', the open will block until another
  1470.      process opens the FIFO for reading, unless `O_NONBLOCK' is specified,
  1471.      in which case the open fails.
  1472.  
  1473. When reading and writing the FIFO, the same considerations apply as for
  1474. regular pipes and sockets, i.e. `read()' will return EOF when all writers
  1475. have closed, and `write()' will raise `SIGPIPE' when there are no readers.
  1476. If `SIGPIPE' is blocked or ignored, the call fails with `EPIPE'.
  1477.  
  1478. 2.10.4 Can I use a named pipe across NFS?
  1479. -----------------------------------------
  1480.  
  1481. No, you can't. There is no facility in the NFS protocol to do this.  (You
  1482. may be able to use a named pipe on an NFS-mounted filesystem to communicate
  1483. between processes on the same client, though.)
  1484.  
  1485. 2.10.5 Can multiple processes write to the pipe simultaneously?
  1486. ---------------------------------------------------------------
  1487.  
  1488. If each piece of data written to the pipe is less than `PIPE_BUF' in size,
  1489. then they will not be interleaved.  However, the boundaries of writes are
  1490. not preserved; when you read from the pipe, the read call will return as
  1491. much data as possible, even if it originated from multiple writes.
  1492.  
  1493. The value of `PIPE_BUF' is guaranteed (by Posix) to be at least 512.  It
  1494. may or may not be defined in `<limits.h>', but it can be queried for
  1495. individual pipes using `pathconf()' or `fpathconf()'.
  1496.  
  1497. 2.10.6 Using named pipes in applications
  1498. ----------------------------------------
  1499.  
  1500.      How can I implement two way communication between one server and
  1501.      several clients?
  1502.  
  1503. It is possible that more than one client is communicating with your server
  1504. at once.  As long as each command they send to the server is smaller than
  1505. `PIPE_BUF' (see above), they can all use the same named pipe to send data
  1506. to the server. All clients can easily know the name of the server's
  1507. incoming fifo.
  1508.  
  1509. However, the server can not use a single pipe to communicate with the
  1510. clients.  If more than one client is reading the same pipe, there is no way
  1511. to ensure that the appropriate client receives a given response.
  1512.  
  1513. A solution is to have the client create its own incoming pipe before
  1514. sending data to the server, or to have the server create its outgoing pipes
  1515. after receiving data from the client.
  1516.  
  1517. Using the client's process ID in the pipe's name is a common way to
  1518. identify them. Using fifos named in this manner, each time the client sends
  1519. a command to the server, it can include its PID as part of the command.
  1520. Any returned data can be sent through the appropriately named pipe.
  1521.  
  1522. 3. Terminal I/O
  1523. ***************
  1524.  
  1525. 3.1 How can I make my program not echo input?
  1526. =============================================
  1527.  
  1528.      How can I make my program not echo input, like login does when asking
  1529.      for your password?
  1530.  
  1531. There is an easy way, and a slightly harder way:
  1532.  
  1533. The easy way, is to use `getpass()', which is probably found on almost all
  1534. Unices. It takes a string to use as a prompt. It will read up to an `EOF'
  1535. or newline and returns a pointer to a static area of memory holding the
  1536. string typed in.
  1537.  
  1538. The harder way is to use `tcgetattr()' and `tcsetattr()', both use a
  1539. `struct termios' to manipulate the terminal. The following two routines
  1540. should allow echoing, and non-echoing mode.
  1541.  
  1542.      #include <stdlib.h>
  1543.      #include <stdio.h>
  1544.      
  1545.      #include <termios.h>
  1546.      #include <string.h>
  1547.      
  1548.      static struct termios stored_settings;
  1549.      
  1550.      void echo_off(void)
  1551.      {
  1552.          struct termios new_settings;
  1553.          tcgetattr(0,&stored_settings);
  1554.          new_settings = stored_settings;
  1555.          new_settings.c_lflag &= (~ECHO);
  1556.          tcsetattr(0,TCSANOW,&new_settings);
  1557.          return;
  1558.      }
  1559.      
  1560.      void echo_on(void)
  1561.      {
  1562.          tcsetattr(0,TCSANOW,&stored_settings);
  1563.          return;
  1564.      }
  1565.  
  1566. Both routines used, are defined by the POSIX standard.
  1567.  
  1568. 3.2 How can I read single characters from the terminal?
  1569. =======================================================
  1570.  
  1571.      How can I read single characters from the terminal? My program is
  1572.      always waiting for the user to press `<RETURN>'.
  1573.  
  1574. Terminals are usually in canonical mode, where input is read in lines after
  1575. it is edited. You may set this into non-canonical mode, where you set how
  1576. many characters should be read before input is given to your program. You
  1577. also may set the timer in non-canonical mode terminals to 0, this timer
  1578. flushs your buffer at set intervals. By doing this, you can use `getc()' to
  1579. grab the key pressed immediately by the user. We use `tcgetattr()' and
  1580. `tcsetattr()' both of which are defined by POSIX to manipulate the
  1581. `termios' structure.
  1582.  
  1583.      #include <stdlib.h>
  1584.      #include <stdio.h>
  1585.      
  1586.      #include <termios.h>
  1587.      #include <string.h>
  1588.      
  1589.      static struct termios stored_settings;
  1590.      
  1591.      void set_keypress(void)
  1592.      {
  1593.          struct termios new_settings;
  1594.      
  1595.          tcgetattr(0,&stored_settings);
  1596.      
  1597.          new_settings = stored_settings;
  1598.      
  1599.          /* Disable canonical mode, and set buffer size to 1 byte */
  1600.          new_settings.c_lflag &= (~ICANON);
  1601.          new_settings.c_cc[VTIME] = 0;
  1602.          new_settings.c_cc[VMIN] = 1;
  1603.      
  1604.          tcsetattr(0,TCSANOW,&new_settings);
  1605.          return;
  1606.      }
  1607.      
  1608.      void reset_keypress(void)
  1609.      {
  1610.          tcsetattr(0,TCSANOW,&stored_settings);
  1611.          return;
  1612.      }
  1613.  
  1614. 3.3 How can I check and see if a key was pressed?
  1615. =================================================
  1616.  
  1617.      How can I check and see if a key was pressed? On DOS I use the
  1618.      `kbhit()' function, but there doesn't seem to be an equivalent?
  1619.  
  1620. If you set the terminal to single-character mode (see previous answer),
  1621. then (on most systems) you can use `select()' or `poll()' to test for
  1622. readability.
  1623.  
  1624. 3.4 How can I move the cursor around the screen?
  1625. ================================================
  1626.  
  1627.      How can I move the cursor around the screen? I want to do full screen
  1628.      editing without using curses.
  1629.  
  1630. Seriously, you probably *don't* want to do this. Curses knows about how to
  1631. handle all sorts of oddities that different terminal types exhibit; while
  1632. the termcap/terminfo data will tell you whether any given terminal type
  1633. possesses any of these oddities, you will probably find that correctly
  1634. handling all the combinations is a *huge* job.
  1635.  
  1636. However, if you insist on getting your hands dirty (so to speak), look into
  1637. the `termcap' functions, particularly `tputs()', `tparm()' and `tgoto()'.
  1638.  
  1639. 3.5 What are pttys?
  1640. ===================
  1641.  
  1642. Pseudo-teletypes (pttys, ptys, other variant abbreviations) are
  1643. pseudo-devices that have two parts: the "master" side, which can be thought
  1644. of as the `user', and the "slave" side, which behaves like a standard tty
  1645. device.
  1646.  
  1647. They exist in order to provide a means to emulate the behaviour of a serial
  1648. terminal under the control of a program. For example, `telnet' uses a
  1649. pseudo-terminal on the remote system; the remote login shell sees the
  1650. behaviour it expects from a tty device, but the master side of the
  1651. pseudo-terminal is being controlled by a daemon that forwards all data over
  1652. the network. They are also used by programs such as `xterm', `expect',
  1653. `script', `screen', `emacs', and many others.
  1654.  
  1655. 3.6 How to handle a serial port or modem?
  1656. =========================================
  1657.  
  1658. The handling of serial devices under Unix is heavily influenced by the
  1659. traditional use of serial terminals. Historically, various combinations of
  1660. ioctls and other hacks were necessary to control the precise behaviour of a
  1661. serial device, but fortunately this is one of the areas that POSIX made
  1662. some efforts to standardise.
  1663.  
  1664. If you're using a system that doesn't understand `<termios.h>',
  1665. `tcsetattr()' and related functions, then you'll have to go elsewhere for
  1666. information (or upgrade your system to something less archaeological).
  1667.  
  1668. There are still significant differences between systems, however, mainly in
  1669. the area of device names, handling of hardware flow control, and modem
  1670. signalling. (Whenever possible, leave the device driver to do all the
  1671. handshaking work, and don't attempt to manipulate handshaking signals
  1672. directly.)
  1673.  
  1674. The basic steps for opening and initialising a serial device are:
  1675.  
  1676.    * `open()' the device; this may require the use of certain flags:
  1677.  
  1678.     `O_NONBLOCK'
  1679.           Opening a dial-in or modem-controlled device will block until
  1680.           carrier is present, unless this flag is used. A nonblocking open
  1681.           gives you the opportunity to disable the modem controls (see
  1682.           CLOCAL below) if necessary.
  1683.  
  1684.     `O_NOCTTY'
  1685.           On 4.4BSD-derived systems this is redundant, but on other systems
  1686.           it controls whether the serial device can become a control
  1687.           terminal for the session. In most cases you probably *don't* want
  1688.           to acquire a control terminal, and should therefore specify this
  1689.           flag, but there are exceptions.
  1690.  
  1691.    * Use `tcgetattr()' to retrieve the current device modes. While one will
  1692.      often ignore most or all of the initial settings thus obtained, it's
  1693.      still a convenient way of initialising a `struct termios'.
  1694.  
  1695.    * Set suitable values for `c_iflag', `c_oflag', `c_cflag', `c_lflag',
  1696.      and `c_cc' in the termios structure. (See below.)
  1697.  
  1698.    * Use `cfsetispeed()' and `cfsetospeed()' to set the desired baud rate.
  1699.      Very few systems allow you to set differing input and output speeds,
  1700.      so as a general rule you should set both to your desired speed.
  1701.  
  1702.    * Use `tcsetattr()' to set the device modes.
  1703.  
  1704.    * You may wish, if you used `O_NONBLOCK' when opening the port, to use
  1705.      `fcntl()' to ensure that `O_NONBLOCK' is turned off again.  Systems
  1706.      seem to differ as to whether a nonblocking open on a tty will affect
  1707.      subsequent `read()' calls; better to be explicit.
  1708.  
  1709. Once you have opened and set up the port, you can then use `read()' and
  1710. `write()' normally. Note that the behaviour of `read()' will be controlled
  1711. by the flag settings you gave to `tcsetattr()'.
  1712.  
  1713. `tcflush()', `tcdrain()', `tcsendbreak()' and `tcflow()' are additional
  1714. useful functions that you should be aware of.
  1715.  
  1716. When you're done with the port, and want to close it, be aware of a very
  1717. nasty little hazard on some systems; if there's any pending output waiting
  1718. to be written to the device (e.g. if output flow is stopped by hardware or
  1719. software handshaking), your process can hang *unkillably* in the `close()'
  1720. call until the output drains. Calling `tcflush()' to discard any pending
  1721. output is probably a wise move.
  1722.  
  1723. (Blocked output on tty devices is by far the most common cause of
  1724. "unkillable" processes in my experience.)
  1725.  
  1726. 3.6.1 Serial device names and types
  1727. -----------------------------------
  1728.  
  1729. The device names used for serial port devices vary quite widely between
  1730. systems. Some examples from different systems are:
  1731.  
  1732.    * `/dev/tty[0-9][a-z]' for direct access devices, and
  1733.      `/dev/tty[0-9][A-Z]' for modem control devices (e.g. SCO Unix)
  1734.  
  1735.    * `/dev/cua[0-9]p[0-9]' for direct access devices, `/dev/cul[0-9]p[0-9]'
  1736.      for dial-out devices and `/dev/ttyd[0-9]p[0-9]' for dial-in devices
  1737.      (e.g. HP-UX)
  1738.  
  1739.    * `/dev/cua[a-z][0-9]' for dial-out devices and `/dev/tty[a-z][0-9]' for
  1740.      dial-in devices (e.g. FreeBSD)
  1741.  
  1742. The precise interaction between the device name used, and the effect on any
  1743. hardware handshake lines is system-, configuration- and hardware-dependant,
  1744. but will usually follow approximately these rules (assuming that the
  1745. hardware is RS-232 DTE):
  1746.  
  1747.    - A successful open of any device should assert DTR and RTS
  1748.  
  1749.    - A blocking open of a modem-control or dial-in device will wait for DCD
  1750.      (and possibly also DSR and/or CTS) to be raised, usually after
  1751.      asserting DTR/RTS.
  1752.  
  1753.    - An open of a dial-out device while an open call to the corresponding
  1754.      dial-in device is blocked waiting for carrier *may or may not* cause
  1755.      the open of the dial-in port to complete. Some systems implement a
  1756.      simple sharing scheme for dial-in and dial-out ports whereby the
  1757.      dial-in port is effectively "put to sleep" while the dial-out port is
  1758.      in use; other systems do not do this, and sharing the port between
  1759.      dial-in and dial-out on such systems requires external cooperation
  1760.      (e.g. use of UUCP lockfiles) to avoid contention problems.
  1761.  
  1762. 3.6.2 Setting up termios flags
  1763. ------------------------------
  1764.  
  1765. Some hints on setting up the termios flags when using a serial device that
  1766. you've opened yourself (as opposed to using your existing control tty):
  1767.  
  1768. 3.6.2.1 c_iflag
  1769. ...............
  1770.  
  1771. You probably want to set *all* the bits in `c_iflag' to 0, unless you want
  1772. to use software flow control (ick) in which case you set `IXON' and `IXOFF'.
  1773.  
  1774. 3.6.2.2 c_oflag
  1775. ...............
  1776.  
  1777. Most of the bits of `c_oflag' are hacks of one sort or another to make
  1778. output to slow terminals work, and as such some newer systems have dropped
  1779. almost all of them as obsolete (especially all the gory output-padding
  1780. options). As with `c_iflag', setting everything to 0 is reasonable for most
  1781. applications.
  1782.  
  1783. 3.6.2.3 c_cflag
  1784. ...............
  1785.  
  1786. When setting the character size, remember to mask using `CSIZE' first; e.g.
  1787. to set 8-bit characters, use:
  1788.          attr.c_cflag &= ~CSIZE;
  1789.          attr.c_cflag |= CS8;
  1790.  
  1791. Other important flags found in `c_cflag' that you probably want to turn
  1792. *on* and `CREAD' and `HUPCL'.
  1793.  
  1794. If you need to generate even parity, then set `PARENB' and clear `PARODD';
  1795. if you need to generate odd parity then set both `PARENB' and `PARODD'. If
  1796. you don't want parity at all, then make sure `PARENB' is clear.
  1797.  
  1798. Clear `CSTOPB' unless you actually need to generate two stop bits.
  1799.  
  1800. Flags for enabling hardware flow control may also be found in `c_cflag',
  1801. but they aren't standardised (pity).
  1802.  
  1803. 3.6.2.4 c_lflag
  1804. ...............
  1805.  
  1806. Most applications will probably want to turn off `ICANON' (canonical, i.e.
  1807. line-based, input processing), `ECHO', and `ISIG'.
  1808.  
  1809. `IEXTEN' is a more complex issue. If you don't turn it off, the
  1810. implementation is allowed to do nonstandard things (like define additional
  1811. control characters in `c_cc') that might cause unexpected results, but you
  1812. might need to leave `IEXTEN' enabled on some systems to get useful features
  1813. like hardware flow control.
  1814.  
  1815. 3.6.2.5 c_cc
  1816. ............
  1817.  
  1818. This is an array of characters that have special meanings on input.  These
  1819. characters are given names like `VINTR', `VSTOP' etc.; the names are
  1820. indexes into the array.
  1821.  
  1822. (Two of these "characters" are not really characters at all, but control
  1823. the behaviour of `read()' when `ICANON' is disabled; these are `VMIN' and
  1824. `VTIME'.)
  1825.  
  1826. The indexes are often referred to as though they were actual variables,
  1827. e.g. "set VMIN to 1" actually means "set c_cc[VMIN] to 1". The shorthand is
  1828. useful and only occasionally confusing.
  1829.  
  1830. Many of the slots in `c_cc' are only used if some other combination of
  1831. flags is set:
  1832.  
  1833. Used only if `ICANON' is set
  1834.      `VEOF', `VEOL', `VERASE', `VKILL' (and also `VEOL2', `VSTATUS' and
  1835.      `VWERASE' if defined and `IEXTEN' is set)
  1836.  
  1837. Used only if `ISIG' is set
  1838.      `VINTR', `VQUIT', `VSUSP' (and also `VDSUSP' if defined and `IEXTEN'
  1839.      is set)
  1840.  
  1841. Used only if `IXON' or `IXOFF' is set
  1842.      `VSTOP', `VSTART'
  1843.  
  1844. Used only if `ICANON' is *not* set
  1845.      `VMIN', `VTIME'
  1846.  
  1847. Implementations may define additional entries in `c_cc'. It may be prudent
  1848. to initialise all the entries to `_POSIX_VDISABLE' (the constant `NCCS'
  1849. gives the array size) before setting the specific values you wish to use.
  1850.  
  1851. `VMIN' and `VTIME' (which may share slots with `VEOF' and `VEOL'
  1852. respectively, depending on the implementation) have the following meaning.
  1853. The value of `VTIME' is (if not 0) always interpreted as a timer in tenths
  1854. of seconds.
  1855.  
  1856. `c_cc[VMIN] > 0, c_cc[VTIME] > 0'
  1857.      `read()' will return when either VMIN bytes of input are available, or
  1858.      if at least one character has been read and VTIME has expired between
  1859.      characters, or if interrupted by a signal.
  1860.  
  1861. `c_cc[VMIN] > 0, c_cc[VTIME] == 0'
  1862.      `read()' will return when VMIN bytes of input are available, or if
  1863.      interrupted. Otherwise it will wait indefinitely.
  1864.  
  1865. `c_cc[VMIN] == 0, c_cc[VTIME] > 0'
  1866.      `read()' will return as soon as any input is available; if VTIME
  1867.      expires with no data arriving, it will return with no characters read.
  1868.      (This conflicts slightly with the end-of-file indication received in
  1869.      the event of modem hangup; using 1 for VMIN and either `alarm()' or
  1870.      `select()' for a timeout avoids this particular problem.)
  1871.  
  1872. `c_cc[VMIN] == 0, c_cc[VTIME] == 0'
  1873.      `read()' will always return immediately; if no data is available it
  1874.      will return with no characters read (with the same problem as above).
  1875.  
  1876. 4. System Information
  1877. *********************
  1878.  
  1879. 4.1 How can I tell how much memory my system has?
  1880. =================================================
  1881.  
  1882. This is another `Frequently Unanswered Question'. In most cases, you should
  1883. not even *attempt* to find out.
  1884.  
  1885. If you really must, then it can usually be done, but in a highly
  1886. system-dependent fashion. For example, on Solaris, you can use
  1887. `sysconf(_SC_PHYS_PAGES)' and `sysconf(_SC_PAGESIZE)'; on FreeBSD, you can
  1888. use `sysctl()'; on Linux you can read and parse `/proc/meminfo' (being
  1889. careful to allow any of the historically valid formats for this file);
  1890. other systems may have their own methods.  I'm not aware of any more
  1891. portable methods.
  1892.  
  1893. For HP-UX (9 and 10), the following code has been contributed:
  1894.  
  1895.      struct pst_static pst;
  1896.      
  1897.      if (pstat_getstatic(&pst, sizeof(pst), (size_t) 1, 0) != -1)
  1898.      {
  1899.          printf(" Page Size: %lu\n", pst.page_size);
  1900.          printf("Phys Pages: %lu\n", pst.physical_memory);
  1901.      }
  1902.  
  1903. 4.2 How do I check a user's password?
  1904. =====================================
  1905.  
  1906. 4.2.1 How do I get a user's password?
  1907. -------------------------------------
  1908.  
  1909. Traditionally user passwords were kept in the `/etc/passwd' file, on most
  1910. UNIX flavours. Which is usually of this format:
  1911.  
  1912. username:password:uid:gid:gecos field:home directory:login shell
  1913.  
  1914. Though this has changed with time, now user information may be kept on
  1915. other hosts, or not necessarily in the `/etc/passwd' file.  Modern
  1916. implementations also made use of `shadow' password files which hold the
  1917. password, along with sensitive information.  This file would be readable
  1918. only by privileged users.
  1919.  
  1920. The password is usually not in clear text, but encrypted due to security
  1921. concerns.
  1922.  
  1923. POSIX defines a suite of routines which can be used to access this database
  1924. for queries. The quickest way to get an individual record for a user is
  1925. with the `getpwnam()' and `getpwuid()' routines. Both return a pointer to a
  1926. struct passwd, which holds the users information in various members.
  1927. `getpwnam()' accepts a string holding the user's name, `getpwuid()' accepts
  1928. a uid (type `uid_t' as defined by POSIX). Both return NULL if they fail.
  1929.  
  1930. However, as explained earlier, a shadow database exists on most modern
  1931. systems to hold sensitive information, namely the password. Some systems
  1932. only return the password if the calling uid is of the superuser, others
  1933. require you to use another suite of functions for the shadow password
  1934. database. If this is the case you need to make use of `getspnam()', which
  1935. accepts a username and returns a struct spwd. Again, in order to
  1936. successfully do this, you will need to have privileges. (On some systems,
  1937. notably HP-UX and SCO, you may need to use `getprpwnam()' instead.)
  1938.  
  1939. 4.2.2 How do I get shadow passwords by uid?
  1940. -------------------------------------------
  1941.  
  1942.      My system uses the getsp* suite of routines to get the sensitive user
  1943.      information. However I do not have `getspuid()', only `getspnam()'.
  1944.      How do I work around this, and get by uid?
  1945.  
  1946. The work around is relatively painless. The following routine should go
  1947. straight into your personal utility library:
  1948.  
  1949.      #include <stdlib.h>
  1950.      #include <stdio.h>
  1951.      
  1952.      #include <pwd.h>
  1953.      #include <shadow.h>
  1954.      
  1955.      struct spwd *getspuid(uid_t pw_uid)
  1956.      {
  1957.        struct spwd *shadow;
  1958.        struct passwd *ppasswd;
  1959.      
  1960.        if( ((ppasswd = getpwuid(pw_uid)) == NULL)
  1961.            || ((shadow = getspnam(ppasswd->pw_name)) == NULL))
  1962.          return NULL;
  1963.      
  1964.        return shadow;
  1965.      }
  1966.  
  1967. The problem is, that some systems do not keep the uid, or other information
  1968. in the shadow database.
  1969.  
  1970. 4.2.3 How do I verify a user's password?
  1971. ----------------------------------------
  1972.  
  1973. The fundamental problem here is, that various authentication systems exist,
  1974. and passwords aren't always what they seem. Also with the traditional one
  1975. way encryption method used by most UNIX flavours (out of the box), the
  1976. encryption algorithm may differ, some systems use a one way DES encryption,
  1977. others like the international release of FreeBSD use MD5.
  1978.  
  1979. The most popular way is to have a one way encryption algorithm, where the
  1980. password cannot be decrypted. Instead the password is taken in clear text
  1981. from input, and encrypted and checked against the encrypted password in the
  1982. database. The details of how to encrypt should really come from your man
  1983. page for `crypt()', but here's a usual version:
  1984.  
  1985.      /* given a plaintext password and an encrypted password, check if
  1986.       * they match; returns 1 if they match, 0 otherwise.
  1987.       */
  1988.      
  1989.      int check_pass(const char *plainpw, const char *cryptpw)
  1990.      {
  1991.          return strcmp(crypt(plainpw,cryptpw), cryptpw) == 0;
  1992.      }
  1993.  
  1994. This works because the salt used in encrypting the password is stored as an
  1995. initial substring of the encrypted value.
  1996.  
  1997. *WARNING:* on some systems, password encryption is actually done with a
  1998. variant of crypt called `bigcrypt()'.
  1999.  
  2000. 5. Miscellaneous programming
  2001. ****************************
  2002.  
  2003. 5.1 How do I compare strings using wildcards?
  2004. =============================================
  2005.  
  2006. The answer to *that* depends on what exactly you mean by `wildcards'.
  2007.  
  2008. There are two quite different concepts that qualify as `wildcards'. They
  2009. are:
  2010.  
  2011. *Filename patterns*
  2012.      These are what the shell uses for filename expansion (`globbing').
  2013.  
  2014. *Regular Expressions*
  2015.      These are used by editors, `grep', etc. for matching text, but they
  2016.      normally *aren't* applied to filenames.
  2017.  
  2018. 5.1.1 How do I compare strings using filename patterns?
  2019. -------------------------------------------------------
  2020.  
  2021. Unless you are unlucky, your system should have a function `fnmatch()' to
  2022. do filename matching. This generally allows only the Bourne shell style of
  2023. pattern; i.e. it recognises `*', `[...]' and `?', but probably won't
  2024. support the more arcane patterns available in the Korn and Bourne-Again
  2025. shells.
  2026.  
  2027. If you don't have this function, then rather than reinvent the wheel, you
  2028. are probably better off snarfing a copy from the BSD or GNU sources.
  2029.  
  2030. Also, for the common cases of matching actual filenames, look for `glob()',
  2031. which will find all existing files matching a pattern.
  2032.  
  2033. 5.1.2 How do I compare strings using regular expressions?
  2034. ---------------------------------------------------------
  2035.  
  2036. There are a number of slightly different syntaxes for regular expressions;
  2037. most systems use at least two: the one recognised by `ed', sometimes known
  2038. as `Basic Regular Expressions', and the one recognised by `egrep',
  2039. `Extended Regular Expressions'. Perl has it's own slightly different
  2040. flavour, as does Emacs.
  2041.  
  2042. To support this multitude of formats, there is a corresponding multitude of
  2043. implementations. Systems will generally have regexp-matching functions
  2044. (usually `regcomp()' and `regexec()') supplied, but be wary; some systems
  2045. have more than one implementation of these functions available, with
  2046. different interfaces. In addition, there are many library implementations
  2047. available. (It's common, BTW, for regexps to be compiled to an internal
  2048. form before use, on the assumption that you may compare several separate
  2049. strings against the same regexp.)
  2050.  
  2051. One library available for this is the `rx' library, available from the GNU
  2052. mirrors. This seems to be under active development, which may be a good or
  2053. a bad thing depending on your point of view :-)
  2054.  
  2055. 5.2 What's the best way to send mail from a program?
  2056. ====================================================
  2057.  
  2058. There are several ways to send email from a Unix program. Which is the best
  2059. method to use in a given situation varies, so I'll present two of them.  A
  2060. third possibility, not covered here, is to connect to a local SMTP port (or
  2061. a smarthost) and use SMTP directly; see RFC 821.
  2062.  
  2063. 5.2.1 The simple method: /bin/mail
  2064. ----------------------------------
  2065.  
  2066. For simple applications, it may be sufficient to invoke `mail' (usually
  2067. `/bin/mail', but could be `/usr/bin/mail' on some systems).
  2068.  
  2069. *WARNING:* Some versions of UCB Mail may execute commands prefixed by `~!'
  2070. or `~|' given in the message body even in non-interactive mode. This can be
  2071. a security risk.
  2072.  
  2073. Invoked as `mail -s 'subject' recipients...' it will take a message body on
  2074. standard input, and supply a default header (including the specified
  2075. subject), and pass the message to `sendmail' for delivery.
  2076.  
  2077. This example mails a test message to `root' on the local system:
  2078.  
  2079.      #include <stdio.h>
  2080.      
  2081.      #define MAILPROG "/bin/mail"
  2082.      
  2083.      int main()
  2084.      {
  2085.          FILE *mail = popen(MAILPROG " -s 'Test Message' root", "w");
  2086.          if (!mail)
  2087.          {
  2088.              perror("popen");
  2089.              exit(1);
  2090.          }
  2091.      
  2092.          fprintf(mail, "This is a test.\n");
  2093.      
  2094.          if (pclose(mail))
  2095.          {
  2096.              fprintf(stderr, "mail failed!\n");
  2097.              exit(1);
  2098.          }
  2099.      }
  2100.  
  2101. If the text to be sent is already in a file, then one can do:
  2102.  
  2103.          system(MAILPROG " -s 'file contents' root </tmp/filename");
  2104.  
  2105. These methods can be extended to more complex cases, but there are many
  2106. pitfalls to watch out for:
  2107.  
  2108.    * If using system() or popen(), you must be very careful about quoting
  2109.      arguments to protect them from filename expansion or word splitting
  2110.  
  2111.    * Constructing command lines from user-specified data is a common source
  2112.      of buffer-overrun errors and other security holes
  2113.  
  2114.    * This method does not allow for CC: or BCC: recipients to be specified
  2115.      (some versions of /bin/mail may allow this, some do not)
  2116.  
  2117. 5.2.2 Invoking the MTA directly: /usr/lib/sendmail
  2118. --------------------------------------------------
  2119.  
  2120. The `mail' program is an example of a "Mail User Agent", a program intended
  2121. to be invoked by the user to send and receive mail, but which does not
  2122. handle the actual transport. A program for transporting mail is called an
  2123. "MTA", and the most commonly found MTA on Unix systems is called
  2124. `sendmail'. There are other MTAs in use, such as `MMDF', but these
  2125. generally include a program that emulates the usual behaviour of `sendmail'.
  2126.  
  2127. Historically, `sendmail' has usually been found in `/usr/lib', but the
  2128. current trend is to move library programs out of `/usr/lib' into
  2129. directories such as `/usr/sbin' or `/usr/libexec'. As a result, one
  2130. normally invokes `sendmail' by its full path, which is system-dependent.
  2131.  
  2132. To understand how `sendmail' behaves, it's useful to understand the concept
  2133. of an "envelope". This is very much like paper mail; the envelope defines
  2134. who the message is to be delivered to, and who it is from (for the purpose
  2135. of reporting errors). Contained in the envelope are the "headers", and the
  2136. "body", separated by a blank line.  The format of the headers is specified
  2137. primarily by RFC 822; see also the MIME RFCs.
  2138.  
  2139. There are two main ways to use `sendmail' to originate a message: either
  2140. the envelope recipients can be explicitly supplied, or `sendmail' can be
  2141. instructed to deduce them from the message headers.  Both methods have
  2142. advantages and disadvantages.
  2143.  
  2144. 5.2.2.1 Supplying the envelope explicitly
  2145. .........................................
  2146.  
  2147. The recipients of a message can simply be specified on the command line.
  2148. This has the drawback that mail addresses can contain characters that give
  2149. `system()' and `popen()' considerable grief, such as single quotes, quoted
  2150. strings etc. Passing these constructs successfully through shell
  2151. interpretation presents pitfalls. (One can do it by replacing any single
  2152. quotes by the sequence single-quote backslash single-quote single-quote,
  2153. then surrounding the entire address with single quotes. Ugly, huh?)
  2154.  
  2155. Some of this unpleasantness can be avoided by eschewing the use of
  2156. `system()' or `popen()', and resorting to `fork()' and `exec()' directly.
  2157. This is sometimes necessary in any event; for example, user-installed
  2158. handlers for SIGCHLD will usually break `pclose()' to a greater or lesser
  2159. extent.
  2160.  
  2161. Here's an example:
  2162.  
  2163.      #include <sys/types.h>
  2164.      #include <sys/wait.h>
  2165.      #include <unistd.h>
  2166.      #include <stdlib.h>
  2167.      #include <fcntl.h>
  2168.      #include <sysexits.h>
  2169.      /* #include <paths.h> if you have it */
  2170.      
  2171.      #ifndef _PATH_SENDMAIL
  2172.      #define _PATH_SENDMAIL "/usr/lib/sendmail"
  2173.      #endif
  2174.      
  2175.      /* -oi means "dont treat . as a message terminator"
  2176.       * remove ,"--" if using a pre-V8 sendmail (and hope that no-one
  2177.       * ever uses a recipient address starting with a hyphen)
  2178.       * you might wish to add -oem (report errors by mail)
  2179.       */
  2180.      
  2181.      #define SENDMAIL_OPTS "-oi","--"
  2182.      
  2183.      /* this is a macro for returning the number of elements in array */
  2184.      
  2185.      #define countof(a) ((sizeof(a))/sizeof((a)[0]))
  2186.      
  2187.      /* send the contents of the file open for reading on FD to the
  2188.       * specified recipients; the file is assumed to contain RFC822 headers
  2189.       * & body, the recipient list is terminated by a NULL pointer; returns
  2190.       * -1 if error detected, otherwise the return value from sendmail
  2191.       * (which uses <sysexits.h> to provide meaningful exit codes)
  2192.       */
  2193.      
  2194.      int send_message(int fd, const char **recipients)
  2195.      {
  2196.          static const char *argv_init[] = { _PATH_SENDMAIL, SENDMAIL_OPTS };
  2197.          const char **argvec = NULL;
  2198.          int num_recip = 0;
  2199.          pid_t pid;
  2200.          int rc;
  2201.          int status;
  2202.      
  2203.          /* count number of recipients */
  2204.      
  2205.          while (recipients[num_recip])
  2206.              ++num_recip;
  2207.      
  2208.          if (!num_recip)
  2209.              return 0;    /* sending to no recipients is successful */
  2210.      
  2211.          /* alloc space for argument vector */
  2212.      
  2213.          argvec = malloc((sizeof char*) * (num_recip+countof(argv_init)+1));
  2214.          if (!argvec)
  2215.              return -1;
  2216.      
  2217.          /* initialise argument vector */
  2218.      
  2219.          memcpy(argvec, argv_init, sizeof(argv_init));
  2220.          memcpy(argvec+countof(argv_init),
  2221.                 recipients, num_recip*sizeof(char*));
  2222.          argvec[num_recip + countof(argv_init)] = NULL;
  2223.      
  2224.          /* may need to add some signal blocking here. */
  2225.      
  2226.          /* fork */
  2227.      
  2228.          switch (pid = fork())
  2229.          {
  2230.          case 0:   /* child */
  2231.      
  2232.              /* Plumbing */
  2233.              if (fd != STDIN_FILENO)
  2234.                  dup2(fd, STDIN_FILENO);
  2235.      
  2236.              /* defined elsewhere -- closes all FDs >= argument */
  2237.              closeall(3);
  2238.      
  2239.              /* go for it: */
  2240.              execv(_PATH_SENDMAIL, argvec);
  2241.              _exit(EX_OSFILE);
  2242.      
  2243.          default:  /* parent */
  2244.      
  2245.              free(argvec);
  2246.              rc = waitpid(pid, &status, 0);
  2247.              if (rc < 0)
  2248.                  return -1;
  2249.              if (WIFEXITED(status))
  2250.                  return WEXITSTATUS(status);
  2251.              return -1;
  2252.      
  2253.          case -1:  /* error */
  2254.              free(argvec);
  2255.              return -1;
  2256.          }
  2257.      }
  2258.  
  2259. 5.2.2.2 Allowing sendmail to deduce the recipients
  2260. ..................................................
  2261.  
  2262. The `-t' option to `sendmail' instructs `sendmail' to parse the headers of
  2263. the message, and use all the recipient-type headers (i.e.  `To:', `Cc:' and
  2264. `Bcc:') to construct the list of envelope recipients. This has the
  2265. advantage of simplifying the `sendmail' command line, but makes it
  2266. impossible to specify recipients other than those listed in the headers.
  2267. (This is not usually a problem.)
  2268.  
  2269. As an example, here's a program to mail a file on standard input to
  2270. specified recipients as a MIME attachment. Some error checks have been
  2271. omitted for brevity. This requires the `mimencode' program from the
  2272. `metamail' distribution.
  2273.  
  2274.      #include <stdio.h>
  2275.      #include <unistd.h>
  2276.      #include <fcntl.h>
  2277.      /* #include <paths.h> if you have it */
  2278.      
  2279.      #ifndef _PATH_SENDMAIL
  2280.      #define _PATH_SENDMAIL "/usr/lib/sendmail"
  2281.      #endif
  2282.      
  2283.      #define SENDMAIL_OPTS "-oi"
  2284.      #define countof(a) ((sizeof(a))/sizeof((a)[0]))
  2285.      
  2286.      char tfilename[L_tmpnam];
  2287.      char command[128+L_tmpnam];
  2288.      
  2289.      void cleanup(void)
  2290.      {
  2291.          unlink(tfilename);
  2292.      }
  2293.      
  2294.      int main(int argc, char **argv)
  2295.      {
  2296.          FILE *msg;
  2297.          int i;
  2298.      
  2299.          if (argc < 2)
  2300.          {
  2301.              fprintf(stderr, "usage: %s recipients...\n", argv[0]);
  2302.              exit(2);
  2303.          }
  2304.      
  2305.          if (tmpnam(tfilename) == NULL
  2306.              || (msg = fopen(tfilename,"w")) == NULL)
  2307.              exit(2);
  2308.      
  2309.          atexit(cleanup);
  2310.      
  2311.          fclose(msg);
  2312.          msg = fopen(tfilename,"a");
  2313.          if (!msg)
  2314.              exit(2);
  2315.      
  2316.          /* construct recipient list */
  2317.      
  2318.          fprintf(msg, "To: %s", argv[1]);
  2319.          for (i = 2; i < argc; i++)
  2320.              fprintf(msg, ",\n\t%s", argv[i]);
  2321.          fputc('\n',msg);
  2322.      
  2323.          /* Subject */
  2324.      
  2325.          fprintf(msg, "Subject: file sent by mail\n");
  2326.      
  2327.          /* sendmail can add it's own From:, Date:, Message-ID: etc. */
  2328.      
  2329.          /* MIME stuff */
  2330.      
  2331.          fprintf(msg, "MIME-Version: 1.0\n");
  2332.          fprintf(msg, "Content-Type: application/octet-stream\n");
  2333.          fprintf(msg, "Content-Transfer-Encoding: base64\n");
  2334.      
  2335.          /* end of headers -- insert a blank line */
  2336.      
  2337.          fputc('\n',msg);
  2338.          fclose(msg);
  2339.      
  2340.          /* invoke encoding program */
  2341.      
  2342.          sprintf(command, "mimencode -b >>%s", tfilename);
  2343.          if (system(command))
  2344.              exit(1);
  2345.      
  2346.          /* invoke mailer */
  2347.      
  2348.          sprintf(command, "%s %s -t <%s",
  2349.                  _PATH_SENDMAIL, SENDMAIL_OPTS, tfilename);
  2350.          if (system(command))
  2351.              exit(1);
  2352.      
  2353.          return 0;
  2354.      }
  2355.  
  2356. 6. Use of tools
  2357. ***************
  2358.  
  2359. 6.1 How can I debug the children after a fork?
  2360. ==============================================
  2361.  
  2362. Depending on the tools available there are various ways:
  2363.  
  2364. Your debugger may have options to select whether to follow the parent or
  2365. the child process (or both) after a `fork()', which may be sufficient for
  2366. some purposes.
  2367.  
  2368. Alternatively, your debugger may have an option which allows you to attach
  2369. to a running process. This can be used to attach to the child process after
  2370. it has been started. If you don't need to examine the very start of the
  2371. child process, this is usually sufficient. Otherwise, you may wish to
  2372. insert a `sleep()' call after the `fork()' in the child process, or a loop
  2373. such as the following:
  2374.  
  2375.      {
  2376.          volatile int f = 1;
  2377.          while(f);
  2378.      }
  2379.  
  2380. which will hang the child process until you explicitly set `f' to 0 using
  2381. the debugger.
  2382.  
  2383. Remember, too, that actively using a debugger isn't the only way to find
  2384. errors in your program; utilities are available to trace system calls and
  2385. signals on many unix flavours, and verbose logging is also often useful.
  2386.  
  2387. 6.2 How to build library from other libraries?
  2388. ==============================================
  2389.  
  2390. Assuming we're talking about an archive (static) library, the easiest way
  2391. is to explode all the constituent libraries into their original objects
  2392. using `ar x' in an empty directory, and combine them all back together.  Of
  2393. course, there is the potential for collision of filenames, but if the
  2394. libraries are large, you probably don't want to be combining them in the
  2395. first place....
  2396.  
  2397. 6.3 How to create shared libraries / dlls?
  2398. ==========================================
  2399.  
  2400. The precise method for creating shared libraries varies between different
  2401. systems. There are two main parts to the process; firstly the objects to be
  2402. included in the shared library must be compiled, usually with options to
  2403. indicate that the code is to be position-independent; secondly, these
  2404. objects are linked together to form the library.
  2405.  
  2406. Here's a trivial example that should illustrate the idea:
  2407.  
  2408.      /* file shrobj.c */
  2409.      
  2410.      const char *myfunc()
  2411.      {
  2412.          return "Hello World";
  2413.      }
  2414.      
  2415.      /* end shrobj.c */
  2416.      
  2417.      /* file hello.c */
  2418.      
  2419.      #include <stdio.h>
  2420.      
  2421.      extern const char *myfunc();
  2422.      
  2423.      main()
  2424.      {
  2425.          printf("%s\n", myfunc());
  2426.          return 0;
  2427.      }
  2428.      
  2429.      /* end hello.c */
  2430.      
  2431.      $ gcc -fpic -c shrobj.c
  2432.      $ gcc -shared -o libshared.so shrobj.o
  2433.      $ gcc hello.c libshared.so
  2434.      $ ./a.out
  2435.      Hello World
  2436.  
  2437. By far the best method if you want the library and build procedure to be
  2438. anything approaching portable is to use GNU Libtool.  This is a small suite
  2439. of utilities which know about the platform-dependent aspects of building
  2440. shared libraries; you can distribute the necessary bits with your program,
  2441. so that when the installer configures the package, he or she can decide
  2442. what libraries to build.  Libtool works fine on systems which do not
  2443. support shared libraries.  It also knows how to hook into GNU Autoconf and
  2444. GNU Automake (if you use those tools to manage your program's build
  2445. procedure).
  2446.  
  2447. If you don't want to use Libtool, then for compilers other than gcc, you
  2448. should change the compiler options as follows:
  2449.  
  2450. AIX 3.2 using xlc (unverified)
  2451.      Drop the `-fpic', and use `-bM:SRE -bE:libshared.exp' instead of
  2452.      `-shared'. You also need to create a file `libshared.exp' containing
  2453.      the list of symbols to export, in this case `myfunc'.  In addition,
  2454.      use `-e _nostart' when linking the library (on newer versions of AIX,
  2455.      I believe this changes to `-bnoentry').
  2456.  
  2457. SCO OpenServer 5 using the SCO Development System (unverified)
  2458.      Shared libraries are only available on OS5 if you compile to ELF
  2459.      format, which requires the `-belf' option. Use `-Kpic' instead of
  2460.      `-fpic', and `cc -belf -G' for the link step.
  2461.  
  2462. Solaris using SparcWorks compilers
  2463.      Use `-pic' instead of `-fpic', and use `ld -G' instead of `gcc
  2464.      -shared'.
  2465.  
  2466. (Submission of additional entries for the above table is encouraged.)
  2467.  
  2468. Other issues to watch out for:
  2469.  
  2470.    * AIX and (I believe) Digital Unix don't require the -fpic option,
  2471.      because all code is position independent.
  2472.  
  2473.    * AIX normally requires that you create an `export file', which is a list
  2474.      of symbols to be exported from the shared library. Some versions of the
  2475.      linker (possibly only the SLHS linker, svld?) have an option to export
  2476.      all symbols.
  2477.  
  2478.    * If you want to refer to your shared library using the conventional
  2479.      `-l' parameter to the linker, you will have to understand how shared
  2480.      libraries are searched for at runtime on your system. The most common
  2481.      method is by using the `LD_LIBRARY_PATH' environment variable, but
  2482.      there is usually an additional option to specify this at link time.
  2483.  
  2484.    * Most implementations record the expected runtime location of the shared
  2485.      library internally. Thus, moving a library from one directory to
  2486.      another may prevent it from working. Many systems have an option to
  2487.      the linker to specify the expected runtime location (the `-R' linker
  2488.      option on Solaris, for example, or the `LD_RUN_PATH' environment
  2489.      variable).
  2490.  
  2491.    * ELF and a.out implementations may have a linker option `-Bsymbolic'
  2492.      which causes internal references within the library to be resolved.
  2493.      Otherwise, on these systems, all symbol resolution is deferred to the
  2494.      final link, and individual routines in the main program can override
  2495.      ones in the library.
  2496.  
  2497. 6.4 Can I replace objects in a shared library?
  2498. ==============================================
  2499.  
  2500. Generally, no.
  2501.  
  2502. On most systems (except AIX), when you link objects to form a shared
  2503. library, it's rather like linking an executable; the objects don't retain
  2504. their individual identity. As a result, it's generally not possible to
  2505. extract or replace individual objects from a shared library.
  2506.  
  2507. 6.5 How can I generate a stack dump from within a running program?
  2508. ==================================================================
  2509.  
  2510. Some systems provide library functions for unwinding the stack, so that you
  2511. can (for example) generate a stack dump in an error-handling function.
  2512. However, these are highly system-specific, and only a minority of systems
  2513. have them.
  2514.  
  2515. A possible workaround is to get your program to invoke a debugger *on
  2516. itself* - the details still vary slightly between systems, but the general
  2517. idea is to do this:
  2518.  
  2519.      void dump_stack(void)
  2520.      {
  2521.          char s[160];
  2522.      
  2523.          sprintf(s, "/bin/echo 'where\ndetach' | dbx -a %d", getpid());
  2524.          system(s);
  2525.      
  2526.          return;
  2527.      }
  2528.  
  2529. You will need to tweak the commands and parameters to dbx according to your
  2530. system, or even substitute another debugger such as `gdb', but this is
  2531. still the most general solution to this particular problem that I've ever
  2532. seen. Kudos to Ralph Corderoy for this one :-)
  2533.  
  2534. Here's a list of the command lines required for some systems:
  2535.  
  2536. Most systems using dbx
  2537.      `"/bin/echo 'where\ndetach' | dbx /path/to/program %d"'
  2538.  
  2539. AIX
  2540.      `"/bin/echo 'where\ndetach' | dbx -a %d"'
  2541.  
  2542. IRIX
  2543.      `"/bin/echo 'where\ndetach' | dbx -p %d"'
  2544.  
  2545. Examples
  2546. ********
  2547.  
  2548. Catching SIGCHLD
  2549. ================
  2550.  
  2551.      #include <sys/types.h>  /* include this before any other sys headers */
  2552.      #include <sys/wait.h>   /* header for waitpid() and various macros */
  2553.      #include <signal.h>     /* header for signal functions */
  2554.      #include <stdio.h>      /* header for fprintf() */
  2555.      #include <unistd.h>     /* header for fork() */
  2556.      
  2557.      void sig_chld(int);     /* prototype for our SIGCHLD handler */
  2558.      
  2559.      int main()
  2560.      {
  2561.          struct sigaction act;
  2562.          pid_t pid;
  2563.      
  2564.          /* Assign sig_chld as our SIGCHLD handler */
  2565.          act.sa_handler = sig_chld;
  2566.      
  2567.          /* We don't want to block any other signals in this example */
  2568.          sigemptyset(&act.sa_mask);
  2569.      
  2570.          /*
  2571.           * We're only interested in children that have terminated, not ones
  2572.           * which have been stopped (eg user pressing control-Z at terminal)
  2573.           */
  2574.          act.sa_flags = SA_NOCLDSTOP;
  2575.      
  2576.          /*
  2577.           * Make these values effective. If we were writing a real
  2578.           * application, we would probably save the old value instead of
  2579.           * passing NULL.
  2580.           */
  2581.          if (sigaction(SIGCHLD, &act, NULL) < 0)
  2582.          {
  2583.              fprintf(stderr, "sigaction failed\n");
  2584.              return 1;
  2585.          }
  2586.      
  2587.          /* Fork */
  2588.          switch (pid = fork())
  2589.          {
  2590.          case -1:
  2591.              fprintf(stderr, "fork failed\n");
  2592.              return 1;
  2593.      
  2594.          case 0:                         /* child -- finish straight away */
  2595.              _exit(7);                   /* exit status = 7 */
  2596.      
  2597.          default:                        /* parent */
  2598.              sleep(10);                  /* give child time to finish */
  2599.          }
  2600.      
  2601.          return 0;
  2602.      }
  2603.      
  2604.      /*
  2605.       * The signal handler function -- only gets called when a SIGCHLD
  2606.       * is received, ie when a child terminates
  2607.       */
  2608.      void sig_chld(int signo)
  2609.      {
  2610.          int status, child_val;
  2611.      
  2612.          /* Wait for any child without blocking */
  2613.          if (waitpid(-1, &status, WNOHANG) < 0)
  2614.          {
  2615.              /*
  2616.               * calling standard I/O functions like fprintf() in a
  2617.               * signal handler is not recommended, but probably OK
  2618.               * in toy programs like this one.
  2619.               */
  2620.              fprintf(stderr, "waitpid failed\n");
  2621.              return;
  2622.          }
  2623.      
  2624.          /*
  2625.           * We now have the info in 'status' and can manipulate it using
  2626.           * the macros in wait.h.
  2627.           */
  2628.          if (WIFEXITED(status))                /* did child exit normally? */
  2629.          {
  2630.              child_val = WEXITSTATUS(status); /* get child's exit status */
  2631.              printf("child's exited normally with status %d\n", child_val);
  2632.          }
  2633.      }
  2634.  
  2635. Reading the process table - SUNOS 4 version
  2636. ===========================================
  2637.  
  2638.      #define _KMEMUSER
  2639.      #include <sys/proc.h>
  2640.      #include <kvm.h>
  2641.      #include <fcntl.h>
  2642.      
  2643.      char regexpstr[256];
  2644.      #define INIT            register char *sp=regexpstr;
  2645.      #define GETC()          (*sp++)
  2646.      #define PEEKC()         (*sp)
  2647.      #define UNGETC(c)       (--sp)
  2648.      #define RETURN(pointer) return(pointer);
  2649.      #define ERROR(val)
  2650.      #include <regexp.h>
  2651.      
  2652.      pid_t
  2653.      getpidbyname(char *name,pid_t skipit)
  2654.      {
  2655.          kvm_t *kd;
  2656.          char **arg;
  2657.          int error;
  2658.          char *p_name=NULL;
  2659.          char expbuf[256];
  2660.          char **freeme;
  2661.          int curpid;
  2662.          struct user * cur_user;
  2663.          struct user myuser;
  2664.          struct proc * cur_proc;
  2665.      
  2666.      
  2667.          if((kd=kvm_open(NULL,NULL,NULL,O_RDONLY,NULL))==NULL){
  2668.              return(-1);
  2669.          }
  2670.          sprintf(regexpstr,"^.*/%s$",name);
  2671.          compile(NULL,expbuf,expbuf+256,'\0');
  2672.      
  2673.          while(cur_proc=kvm_nextproc(kd)){
  2674.              curpid = cur_proc->p_pid;
  2675.              if((cur_user=kvm_getu(kd,cur_proc))!=NULL){
  2676.                  error=kvm_getcmd(kd,cur_proc,cur_user,&arg,NULL);
  2677.                  if(error==-1){
  2678.                      if(cur_user->u_comm[0]!='\0'){
  2679.                          p_name=cur_user->u_comm;
  2680.                      }
  2681.                  }
  2682.                  else{
  2683.                      p_name=arg[0];
  2684.                  }
  2685.              }
  2686.              if(p_name){
  2687.                  if(!strcmp(p_name,name)){
  2688.                      if(error!=-1){
  2689.                          free(arg);
  2690.                      }
  2691.                      if(skipit!=-1 && ourretval==skipit){
  2692.                          ourretval=-1;
  2693.                      }
  2694.                      else{
  2695.                          close(fd);
  2696.                          break;
  2697.                      }
  2698.                      break;
  2699.                  }
  2700.                  else{
  2701.                      if(step(p_name,expbuf)){
  2702.                          if(error!=-1){
  2703.                              free(arg);
  2704.                          }
  2705.                          break;
  2706.                      }
  2707.                  }
  2708.              }
  2709.              if(error!=-1){
  2710.                  free(arg);
  2711.              }
  2712.              p_name=NULL;
  2713.          }
  2714.          kvm_close(kd);
  2715.          if(p_name!=NULL){
  2716.              return(curpid);
  2717.          }
  2718.          return (-1);
  2719.      }
  2720.  
  2721. Reading the process table - SYSV version
  2722. ========================================
  2723.  
  2724.      pid_t
  2725.      getpidbyname(char *name,pid_t skipit)
  2726.      {
  2727.          DIR  *dp;
  2728.          struct dirent *dirp;
  2729.          prpsinfo_t retval;
  2730.          int fd;
  2731.          pid_t ourretval=-1;
  2732.      
  2733.          if((dp=opendir("/proc"))==NULL){
  2734.              return -1;
  2735.          }
  2736.          chdir("/proc");
  2737.          while((dirp=readdir(dp))!=NULL){
  2738.              if(dirp->d_name[0]!='.'){
  2739.                  if((fd=open(dirp->d_name,O_RDONLY))!=-1){
  2740.                      if(ioctl(fd,PIOCPSINFO,&retval)!=-1){
  2741.                          if(!strcmp(retval.pr_fname,name)){
  2742.                              ourretval=(pid_t)atoi(dirp->d_name);
  2743.                              if(skipit!=-1 && ourretval==skipit){
  2744.                                  ourretval=-1;
  2745.                              }
  2746.                              else{
  2747.                                  close(fd);
  2748.                                  break;
  2749.                              }
  2750.                          }
  2751.                      }
  2752.                      close(fd);
  2753.                  }
  2754.              }
  2755.          }
  2756.          closedir(dp);
  2757.          return ourretval;
  2758.      }
  2759.  
  2760. Reading the process table - AIX 4.2 version
  2761. ===========================================
  2762.  
  2763.      #include <stdio.h>
  2764.      #include <procinfo.h>
  2765.      
  2766.      int getprocs(struct procsinfo *, int, struct fdsinfo *,
  2767.                   int, pid_t *, int);
  2768.      
  2769.      pid_t getpidbyname(char *name, pid_t *nextPid)
  2770.      {
  2771.        struct procsinfo  pi;
  2772.        pid_t             retval = (pid_t) -1;
  2773.        pid_t             pid;
  2774.      
  2775.        pid = *nextPid;
  2776.      
  2777.        while(1)
  2778.        {
  2779.          if(getprocs(&pi, sizeof pi, 0, 0, &pid, 1) != 1)
  2780.            break;
  2781.      
  2782.          if(!strcmp(name, pi.pi_comm))
  2783.          {
  2784.            retval = pi.pi_pid;
  2785.            *nextPid = pid;
  2786.            break;
  2787.          }
  2788.        }
  2789.      
  2790.        return retval;
  2791.      }
  2792.      
  2793.      int main(int argc, char *argv[])
  2794.      {
  2795.        int   curArg;
  2796.        pid_t pid;
  2797.        pid_t nextPid;
  2798.      
  2799.        if(argc == 1)
  2800.        {
  2801.          printf("syntax: %s <program> [program ...]\n",argv[0]);
  2802.          exit(1);
  2803.        }
  2804.      
  2805.        for(curArg = 1; curArg < argc; curArg++)
  2806.        {
  2807.          printf("Process IDs for %s\n", argv[curArg]);
  2808.      
  2809.          for(nextPid = 0, pid = 0; pid != -1; )
  2810.            if((pid = getpidbyname(argv[curArg], &nextPid)) != -1)
  2811.              printf("\t%d\n", pid);
  2812.        }
  2813.      }
  2814.  
  2815. Reading the process table using popen and ps
  2816. ============================================
  2817.  
  2818.      #include <stdio.h>      /* FILE, sprintf, fgets, puts */
  2819.      #include <stdlib.h>     /* atoi, exit, EXIT_SUCCESS */
  2820.      #include <string.h>     /* strtok, strcmp */
  2821.      #include <sys/types.h>  /* pid_t */
  2822.      #include <sys/wait.h>   /* WIFEXITED, WEXITSTATUS */
  2823.      
  2824.      char *procname(pid_t pid)
  2825.      {
  2826.         static char line[133], command[80], *linep, *token, *cmd;
  2827.         FILE *fp;
  2828.         int status;
  2829.      
  2830.         if (0 == pid) return (char *)0;
  2831.      
  2832.         sprintf(command, "ps -p %d 2>/dev/null", pid);
  2833.         fp = popen(command, "r");
  2834.         if ((FILE *)0 == fp) return (char *)0;
  2835.      
  2836.         /* read the header line */
  2837.         if ((char *)0 == fgets(line, sizeof line, fp))
  2838.         {
  2839.            pclose(fp);
  2840.            return (char *)0;
  2841.         }
  2842.      
  2843.         /* figure out where the command name is from the column headings.
  2844.          * (BSD-ish machines put the COMMAND in the 5th column, while SysV
  2845.          * seems to put CMD or COMMAND in the 4th column.)
  2846.          */
  2847.         for (linep = line; ; linep = (char *)0)
  2848.         {
  2849.            if ((char *)0 == (token = strtok(linep, " \t\n")))
  2850.            {
  2851.               pclose(fp);
  2852.               return (char *)0;
  2853.            }
  2854.            if (0 == strcmp("COMMAND", token) || 0 == strcmp("CMD", token))
  2855.            { /*  we found the COMMAND column */
  2856.               cmd = token;
  2857.               break;
  2858.            }
  2859.         }
  2860.      
  2861.         /* read the ps(1) output line */
  2862.         if ((char *)0 == fgets(line, sizeof line, fp))
  2863.         {
  2864.            pclose(fp);
  2865.            return (char *)0;
  2866.         }
  2867.      
  2868.         /* grab the "word" underneath the command heading... */
  2869.         if ((char *)0 == (token = strtok(cmd, " \t\n")))
  2870.         {
  2871.            pclose(fp);
  2872.            return (char *)0;
  2873.         }
  2874.      
  2875.         status = pclose(fp);
  2876.         if (!WIFEXITED(status) || 0 != WEXITSTATUS(status))
  2877.           return (char *)0;
  2878.      
  2879.         return token;
  2880.      }
  2881.      
  2882.      int main(int argc, char *argv[])
  2883.      {
  2884.         puts(procname(atoi(argv[1])));
  2885.         exit(EXIT_SUCCESS);
  2886.      }
  2887.  
  2888. Daemon utility functions
  2889. ========================
  2890.  
  2891.      #include <unistd.h>
  2892.      #include <stdlib.h>
  2893.      #include <fcntl.h>
  2894.      #include <signal.h>
  2895.      #include <sys/types.h>
  2896.      #include <sys/wait.h>
  2897.      #include <errno.h>
  2898.      
  2899.      /* closeall() -- close all FDs >= a specified value */
  2900.      
  2901.      void closeall(int fd)
  2902.      {
  2903.          int fdlimit = sysconf(_SC_OPEN_MAX);
  2904.      
  2905.          while (fd < fdlimit)
  2906.            close(fd++);
  2907.      }
  2908.      
  2909.      /* daemon() - detach process from user and disappear into the background
  2910.       * returns -1 on failure, but you can't do much except exit in that case
  2911.       * since we may already have forked. This is based on the BSD version,
  2912.       * so the caller is responsible for things like the umask, etc.
  2913.       */
  2914.      
  2915.      /* believed to work on all Posix systems */
  2916.      
  2917.      int daemon(int nochdir, int noclose)
  2918.      {
  2919.          switch (fork())
  2920.          {
  2921.              case 0:  break;
  2922.              case -1: return -1;
  2923.              default: _exit(0);          /* exit the original process */
  2924.          }
  2925.      
  2926.          if (setsid() < 0)               /* shoudn't fail */
  2927.            return -1;
  2928.      
  2929.          /* dyke out this switch if you want to acquire a control tty in */
  2930.          /* the future -- not normally advisable for daemons */
  2931.      
  2932.          switch (fork())
  2933.          {
  2934.              case 0:  break;
  2935.              case -1: return -1;
  2936.              default: _exit(0);
  2937.          }
  2938.      
  2939.          if (!nochdir)
  2940.            chdir("/");
  2941.      
  2942.          if (!noclose)
  2943.          {
  2944.              closeall(0);
  2945.              open("/dev/null",O_RDWR);
  2946.              dup(0); dup(0);
  2947.          }
  2948.      
  2949.          return 0;
  2950.      }
  2951.      
  2952.      /* fork2() -- like fork, but the new process is immediately orphaned
  2953.       *            (won't leave a zombie when it exits)
  2954.       * Returns 1 to the parent, not any meaningful pid.
  2955.       * The parent cannot wait() for the new process (it's unrelated).
  2956.       */
  2957.      
  2958.      /* This version assumes that you *haven't* caught or ignored SIGCHLD. */
  2959.      /* If you have, then you should just be using fork() instead anyway.  */
  2960.      
  2961.      int fork2()
  2962.      {
  2963.          pid_t pid;
  2964.          int rc;
  2965.          int status;
  2966.      
  2967.          if (!(pid = fork()))
  2968.          {
  2969.              switch (fork())
  2970.              {
  2971.                case 0:  return 0;
  2972.                case -1: _exit(errno);    /* assumes all errnos are <256 */
  2973.                default: _exit(0);
  2974.              }
  2975.          }
  2976.      
  2977.          if (pid < 0 || waitpid(pid,&status,0) < 0)
  2978.            return -1;
  2979.      
  2980.          if (WIFEXITED(status))
  2981.            if (WEXITSTATUS(status) == 0)
  2982.              return 1;
  2983.            else
  2984.              errno = WEXITSTATUS(status);
  2985.          else
  2986.            errno = EINTR;  /* well, sort of :-) */
  2987.      
  2988.          return -1;
  2989.      }
  2990.  
  2991. An example of using the above functions:
  2992.  
  2993.      #include <sys/types.h>
  2994.      #include <sys/socket.h>
  2995.      #include <netinet/in.h>
  2996.      #include <stdio.h>
  2997.      #include <stdlib.h>
  2998.      #include <syslog.h>
  2999.      #include <errno.h>
  3000.      
  3001.      int daemon(int,int);
  3002.      int fork2(void);
  3003.      void closeall(int);
  3004.      
  3005.      #define TCP_PORT 8888
  3006.      
  3007.      void errexit(const char *str)
  3008.      {
  3009.          syslog(LOG_INFO, "%s failed: %d (%m)", str, errno);
  3010.          exit(1);
  3011.      }
  3012.      
  3013.      void errreport(const char *str)
  3014.      {
  3015.          syslog(LOG_INFO, "%s failed: %d (%m)", str, errno);
  3016.      }
  3017.      
  3018.      /* the actual child process is here. */
  3019.      
  3020.      void run_child(int sock)
  3021.      {
  3022.          FILE *in = fdopen(sock,"r");
  3023.          FILE *out = fdopen(sock,"w");
  3024.          int ch;
  3025.      
  3026.          setvbuf(in, NULL, _IOFBF, 1024);
  3027.          setvbuf(out, NULL, _IOLBF, 1024);
  3028.      
  3029.          while ((ch = fgetc(in)) != EOF)
  3030.            fputc(toupper(ch), out);
  3031.      
  3032.          fclose(out);
  3033.      }
  3034.      
  3035.      /* This is the daemon's main work -- listen for connections and spawn */
  3036.      
  3037.      void process()
  3038.      {
  3039.          struct sockaddr_in addr;
  3040.          int addrlen = sizeof(addr);
  3041.          int sock = socket(AF_INET, SOCK_STREAM, 0);
  3042.          int flag = 1;
  3043.          int rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
  3044.                              &flag, sizeof(flag));
  3045.      
  3046.          if (rc < 0)
  3047.            errexit("setsockopt");
  3048.      
  3049.          addr.sin_family = AF_INET;
  3050.          addr.sin_port = htons(TCP_PORT);
  3051.          addr.sin_addr.s_addr = INADDR_ANY;
  3052.      
  3053.          rc = bind(sock, (struct sockaddr *) &addr, addrlen);
  3054.          if (rc < 0)
  3055.            errexit("bind");
  3056.      
  3057.          rc = listen(sock, 5);
  3058.          if (rc < 0)
  3059.            errexit("listen");
  3060.      
  3061.          for (;;)
  3062.          {
  3063.              rc = accept(sock, (struct sockaddr *) &addr, &addrlen);
  3064.      
  3065.              if (rc >= 0)
  3066.                switch (fork2())
  3067.                {
  3068.                  case 0:  close(sock); run_child(rc); _exit(0);
  3069.                  case -1: errreport("fork2"); close(rc); break;
  3070.                  default: close(rc);
  3071.                }
  3072.          }
  3073.      }
  3074.      
  3075.      int main()
  3076.      {
  3077.          if (daemon(0,0) < 0)
  3078.          {
  3079.              perror("daemon");
  3080.              exit(2);
  3081.          }
  3082.      
  3083.          openlog("test", LOG_PID, LOG_DAEMON);
  3084.      
  3085.          process();
  3086.      
  3087.          return 0;
  3088.      }
  3089.  
  3090. Modem handling example
  3091. ======================
  3092.  
  3093.      /* issue some simple modem commands
  3094.       * requires the name of a serial device (preferably a dial-out device,
  3095.       * or a non-modem-control device) as its only parameter.
  3096.       * If you don't have functional dial-out devices, then move CLOCAL
  3097.       * to CFLAGS_TO_SET instead.
  3098.       */
  3099.      
  3100.      #include <stdio.h>
  3101.      #include <stdlib.h>
  3102.      #include <fcntl.h>
  3103.      #include <unistd.h>
  3104.      #include <sys/types.h>
  3105.      #include <sys/time.h>
  3106.      #include <sys/ioctl.h>   /* maybe; system-dependent */
  3107.      #include <termios.h>
  3108.      #include <errno.h>
  3109.      #include <string.h>
  3110.      #include <ctype.h>
  3111.      
  3112.      #define CFLAGS_TO_SET (CREAD | HUPCL)
  3113.      #define CFLAGS_TO_CLEAR (CSTOPB | PARENB | CLOCAL)
  3114.      
  3115.      enum flowmode { NoFlow, HardFlow, SoftFlow };
  3116.      
  3117.      /* system-dependent */
  3118.      #define CFLAGS_HARDFLOW (CRTSCTS)
  3119.      
  3120.      
  3121.      #define EXAMPLE_BAUD B19200
  3122.      #define EXAMPLE_FLOW HardFlow
  3123.      
  3124.      
  3125.      static void die(const char *msg)
  3126.      {
  3127.          fprintf(stderr, "%s\n", msg);
  3128.          exit(1);
  3129.      }
  3130.      
  3131.      static int close_and_complain(int fd, const char *msg, int err)
  3132.      {
  3133.          fprintf(stderr, "%s: %s\n", msg, strerror(err));
  3134.          if (fd >= 0)
  3135.              close(fd);
  3136.          errno = err;
  3137.          return -1;
  3138.      }
  3139.      
  3140.      
  3141.      int open_port(const char *name, speed_t baud, enum flowmode flow)
  3142.      {
  3143.          int flags;
  3144.          struct termios attr;
  3145.      
  3146.          int fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY);
  3147.      
  3148.          if (fd < 0)
  3149.              return close_and_complain(-1, "open", errno);
  3150.      
  3151.          /* set vaguely sensibe settings */
  3152.      
  3153.          if (tcgetattr(fd, &attr) < 0)
  3154.              return close_and_complain(fd, "tcgetattr", errno);
  3155.      
  3156.          /* no special input or output processing */
  3157.      
  3158.          attr.c_iflag = (flow == SoftFlow) ? (IXON | IXOFF) : 0;
  3159.          attr.c_oflag = 0;
  3160.      
  3161.          /* set 8-bit character size and miscellanous control modes */
  3162.      
  3163.          attr.c_cflag &= ~(CSIZE | CFLAGS_TO_CLEAR | CFLAGS_HARDFLOW);
  3164.          attr.c_cflag |= (CS8 | CFLAGS_TO_SET);
  3165.          if (flow == HardFlow)
  3166.              attr.c_cflag |= CFLAGS_HARDFLOW;
  3167.      
  3168.          /* local modes */
  3169.      
  3170.          attr.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ISIG);
  3171.      
  3172.          /* special characters -- most disabled by prior settings anyway */
  3173.      
  3174.          {
  3175.              int i;
  3176.      #ifdef _POSIX_VDISABLE
  3177.              attr.c_cc[0] = _POSIX_VDISABLE;
  3178.      #else
  3179.              attr.c_cc[0] = fpathconf(fd, _PC_VDISABLE);
  3180.      #endif
  3181.              for (i = 1; i < NCCS; i++)
  3182.                  attr.c_cc[i] = attr.c_cc[0];
  3183.          }
  3184.      
  3185.          attr.c_cc[VSTART] = 0x11;
  3186.          attr.c_cc[VSTOP] = 0x13;
  3187.      
  3188.          /* timing controls for read() */
  3189.      
  3190.          attr.c_cc[VMIN] = 1;
  3191.          attr.c_cc[VTIME] = 0;
  3192.      
  3193.          /* baud rate */
  3194.      
  3195.          cfsetispeed(&attr, baud);
  3196.          cfsetospeed(&attr, baud);
  3197.      
  3198.          /* write settings */
  3199.      
  3200.          if (tcsetattr(fd, TCSANOW, &attr) < 0)
  3201.              return close_and_complain(fd, "tcsetattr", errno);
  3202.      
  3203.          /* turn off O_NONBLOCK if the device remembered it */
  3204.      
  3205.          flags = fcntl(fd, F_GETFL, 0);
  3206.          if (flags < 0)
  3207.              return close_and_complain(fd, "fcntl(GETFL)", errno);
  3208.          if (fcntl(fd, F_SETFL, flags & ~O_NONBLOCK) < 0)
  3209.              return close_and_complain(fd, "fcntl(SETFL)", errno);
  3210.      
  3211.          return fd;
  3212.      }
  3213.      
  3214.      /* some simple timing utilities */
  3215.      
  3216.      /* add SECS and USECS to *TV */
  3217.      
  3218.      static void timeradd(struct timeval *tv, long secs, long usecs)
  3219.      {
  3220.          tv->tv_sec += secs;
  3221.          if ((tv->tv_usec += usecs) >= 1000000)
  3222.          {
  3223.              tv->tv_sec += tv->tv_usec / 1000000;
  3224.              tv->tv_usec %= 1000000;
  3225.          }
  3226.      }
  3227.      
  3228.      /* Set *RES = *A - *B, returning the sign of the result */
  3229.      
  3230.      static int timersub(struct timeval *res,
  3231.                          const struct timeval *a, const struct timeval *b)
  3232.      {
  3233.          long sec = a->tv_sec - b->tv_sec;
  3234.          long usec = a->tv_usec - b->tv_usec;
  3235.      
  3236.          if (usec < 0)
  3237.              usec += 1000000, --sec;
  3238.      
  3239.          res->tv_sec = sec;
  3240.          res->tv_usec = usec;
  3241.      
  3242.          return (sec < 0) ? (-1) : ((sec == 0 && usec == 0) ? 0 : 1);
  3243.      }
  3244.      
  3245.      
  3246.      /* this doesn't try and cope with pathological strings (e.g. ababc)
  3247.       * timeout is in millisecs
  3248.       * A more usual approach to this is to use alarm() for the timeout.
  3249.       * This example avoids signal handling for simplicity and to illustrate
  3250.       * an alternative approach
  3251.       */
  3252.      
  3253.      int expect(int fd, const char *str, int timeo)
  3254.      {
  3255.          int matchlen = 0;
  3256.          int len = strlen(str);
  3257.          struct timeval now,end,left;
  3258.          fd_set fds;
  3259.          char c;
  3260.      
  3261.          gettimeofday(&end, NULL);
  3262.          timeradd(&end, timeo/1000, timeo%1000);
  3263.      
  3264.          while (matchlen < len)
  3265.          {
  3266.              gettimeofday(&now, NULL);
  3267.              if (timersub(&left, &end, &now) <= 0)
  3268.                  return -1;
  3269.      
  3270.              FD_ZERO(&fds);
  3271.              FD_SET(fd, &fds);
  3272.              if (select(fd+1, &fds, NULL, NULL, &left) <= 0)
  3273.                  return -1;
  3274.      
  3275.              if (read(fd, &c, 1) != 1)
  3276.                  return -1;
  3277.      
  3278.              if (isprint((unsigned char)c) || c == '\n' || c == '\r')
  3279.                  putchar(c);
  3280.              else
  3281.                  printf("\\x%02x", c);
  3282.      
  3283.              if (c == str[matchlen])
  3284.                  ++matchlen;
  3285.              else
  3286.                  matchlen = 0;
  3287.          }
  3288.      
  3289.          return 0;
  3290.      }
  3291.      
  3292.      
  3293.      int main(int argc, char **argv)
  3294.      {
  3295.          int fd;
  3296.          unsigned char c;
  3297.      
  3298.          if (argc < 2)
  3299.              die("no port specified");
  3300.      
  3301.          setvbuf(stdout, NULL, _IONBF, 0);
  3302.      
  3303.          fd = open_port(argv[1], EXAMPLE_BAUD, EXAMPLE_FLOW);
  3304.          if (fd < 0)
  3305.              die("cannot open port");
  3306.      
  3307.          write(fd, "AT\r", 3);
  3308.          if (expect(fd, "OK", 5000) < 0)
  3309.          {
  3310.              write(fd, "AT\r", 3);
  3311.              if (expect(fd, "OK", 5000) < 0)
  3312.              {
  3313.                  tcflush(fd, TCIOFLUSH);
  3314.                  close(fd);
  3315.                  die("no response to AT");
  3316.              }
  3317.          }
  3318.      
  3319.          write(fd, "ATI4\r", 5);
  3320.          expect(fd, "OK", 10000);
  3321.      
  3322.          putchar('\n');
  3323.      
  3324.          tcflush(fd, TCIOFLUSH);
  3325.          close(fd);
  3326.      
  3327.          return 0;
  3328.      }
  3329.  
  3330. Job Control example
  3331. ===================
  3332.  
  3333.  
  3334.      /* functions to spawn foreground/background jobs */
  3335.      
  3336.      #include <stdio.h>
  3337.      #include <unistd.h>
  3338.      #include <stdlib.h>
  3339.      #include <fcntl.h>
  3340.      #include <signal.h>
  3341.      #include <sys/types.h>
  3342.      #include <sys/wait.h>
  3343.      #include <errno.h>
  3344.      
  3345.      
  3346.      /* Some of the functions below fail if the control tty can't be
  3347.       * located, or if the calling process isn't in the foreground. In the
  3348.       * first case, we are assuming that a foreground process will have the
  3349.       * ctty open on either stdin, stdout or stderr, and we return ENOTTY
  3350.       * if it isn't. In the second case, we return EPERM if a
  3351.       * non-foreground process attempts to put something into the
  3352.       * foreground (probably overly paranoid) except for the special case
  3353.       * of foreground_self().
  3354.       */
  3355.      
  3356.      
  3357.      /* assign the terminal (open on ctty) to a specific pgrp. This wrapper
  3358.       * around tcsetpgrp() is needed only because of extreme bogosity on the
  3359.       * part of POSIX; conforming systems deliver STGTTOU if tcsetpgrp is
  3360.       * called from a non-foreground process (which it almost invariably is).
  3361.       * A triumph of spurious consistency over common sense.
  3362.       */
  3363.      
  3364.      int assign_terminal(int ctty, pid_t pgrp)
  3365.      {
  3366.          sigset_t sigs;
  3367.          sigset_t oldsigs;
  3368.          int rc;
  3369.      
  3370.          sigemptyset(&sigs);
  3371.          sigaddset(&sigs,SIGTTOU);
  3372.          sigprocmask(SIG_BLOCK, &sigs, &oldsigs);
  3373.      
  3374.          rc = tcsetpgrp(ctty, pgrp);
  3375.      
  3376.          sigprocmask(SIG_SETMASK, &oldsigs, NULL);
  3377.      
  3378.          return rc;
  3379.      }
  3380.      
  3381.      
  3382.      /* Like fork(), but does job control. FG is true if the newly-created
  3383.       * process is to be placed in the foreground. (This implicitly puts
  3384.       * the calling process in the background, so watch out for tty I/O
  3385.       * after doing this.) PGRP is -1 to create a new job, in which case
  3386.       * the returned pid is also the pgrp of the new job, or specifies an
  3387.       * existing job in the same session (normally used only for starting
  3388.       * second or subsequent process in a pipeline).  */
  3389.      
  3390.      pid_t spawn_job(int fg, pid_t pgrp)
  3391.      {
  3392.          int ctty = -1;
  3393.          pid_t pid;
  3394.      
  3395.          /* If spawning a *new* foreground job, require that at least one
  3396.           * of stdin, stdout or stderr refer to the control tty, and that
  3397.           * the current process is in the foreground.
  3398.           * Only check for controlling tty if starting a new foreground
  3399.           * process in an existing job.
  3400.           * A session without a control tty can only have background jobs
  3401.           */
  3402.      
  3403.          if (fg)
  3404.          {
  3405.              pid_t curpgrp;
  3406.      
  3407.              if ((curpgrp = tcgetpgrp(ctty = 2)) < 0
  3408.                  && (curpgrp = tcgetpgrp(ctty = 0)) < 0
  3409.                  && (curpgrp = tcgetpgrp(ctty = 1)) < 0)
  3410.                  return errno = ENOTTY, (pid_t)-1;
  3411.      
  3412.              if (pgrp < 0 && curpgrp != getpgrp())
  3413.                  return errno = EPERM, (pid_t)-1;
  3414.          }
  3415.      
  3416.          switch (pid = fork())
  3417.          {
  3418.              case -1: /* fork failure */
  3419.                  return pid;
  3420.      
  3421.              case 0: /* child */
  3422.      
  3423.                  /* establish new process group, and put ourselves in
  3424.                   * foreground if necessary
  3425.                   * unclear what to do if setpgid fails ("can't happen")
  3426.                   */
  3427.      
  3428.                  if (pgrp < 0)
  3429.                      pgrp = getpid();
  3430.      
  3431.                  if (setpgid(0,pgrp) == 0 && fg)
  3432.                      assign_terminal(ctty, pgrp);
  3433.      
  3434.                  return 0;
  3435.      
  3436.              default: /* parent */
  3437.      
  3438.                  /* establish child process group here too. */
  3439.      
  3440.                  if (pgrp < 0)
  3441.                      pgrp = pid;
  3442.      
  3443.                  setpgid(pid, pgrp);
  3444.      
  3445.                  return pid;
  3446.          }
  3447.      
  3448.          /*NOTREACHED*/
  3449.      }
  3450.      
  3451.      
  3452.      /* Kill job PGRP with signal SIGNO */
  3453.      
  3454.      int kill_job(pid_t pgrp, int signo)
  3455.      {
  3456.          return kill(-pgrp, signo);
  3457.      }
  3458.      
  3459.      
  3460.      /* Suspend job PGRP */
  3461.      
  3462.      int suspend_job(pid_t pgrp)
  3463.      {
  3464.          return kill_job(pgrp, SIGSTOP);
  3465.      }
  3466.      
  3467.      
  3468.      /* Resume job PGRP in background */
  3469.      
  3470.      int resume_job_bg(pid_t pgrp)
  3471.      {
  3472.          return kill_job(pgrp, SIGCONT);
  3473.      }
  3474.      
  3475.      
  3476.      /* resume job PGRP in foreground */
  3477.      
  3478.      int resume_job_fg(pid_t pgrp)
  3479.      {
  3480.          pid_t curpgrp;
  3481.          int ctty;
  3482.      
  3483.          if ((curpgrp = tcgetpgrp(ctty = 2)) < 0
  3484.              && (curpgrp = tcgetpgrp(ctty = 0)) < 0
  3485.              && (curpgrp = tcgetpgrp(ctty = 1)) < 0)
  3486.              return errno = ENOTTY, (pid_t)-1;
  3487.      
  3488.          if (curpgrp != getpgrp())
  3489.              return errno = EPERM, (pid_t)-1;
  3490.      
  3491.          if (assign_terminal(ctty, pgrp) < 0)
  3492.              return -1;
  3493.      
  3494.          return kill_job(pgrp, SIGCONT);
  3495.      }
  3496.      
  3497.      
  3498.      /* put ourselves in the foreground, e.g. after suspending a foreground
  3499.       * job
  3500.       */
  3501.      
  3502.      int foreground_self()
  3503.      {
  3504.          pid_t curpgrp;
  3505.          int ctty;
  3506.      
  3507.          if ((curpgrp = tcgetpgrp(ctty = 2)) < 0
  3508.              && (curpgrp = tcgetpgrp(ctty = 0)) < 0
  3509.              && (curpgrp = tcgetpgrp(ctty = 1)) < 0)
  3510.              return errno = ENOTTY, (pid_t)-1;
  3511.      
  3512.          return assign_terminal(ctty, getpgrp());
  3513.      }
  3514.      
  3515.      
  3516.      /* closeall() - close all FDs >= a specified value */
  3517.      
  3518.      void closeall(int fd)
  3519.      {
  3520.          int fdlimit = sysconf(_SC_OPEN_MAX);
  3521.      
  3522.          while (fd < fdlimit)
  3523.              close(fd++);
  3524.      }
  3525.      
  3526.      
  3527.      /* like system(), but executes the specified command as a background
  3528.       * job, returning the pid of the shell process (which is also the pgrp
  3529.       * of the job, suitable for kill_job etc.)
  3530.       * If INFD, OUTFD or ERRFD are non-NULL, then a pipe will be opened and
  3531.       * a descriptor for the parent end of the relevent pipe stored there.
  3532.       * If any of these are NULL, they will be redirected to /dev/null in the
  3533.       * child.
  3534.       * Also closes all FDs > 2 in the child process (an oft-overlooked task)
  3535.       */
  3536.      
  3537.      pid_t spawn_background_command(const char *cmd,
  3538.                                     int *infd, int *outfd, int *errfd)
  3539.      {
  3540.          int nullfd = -1;
  3541.          int pipefds[3][2];
  3542.          int error = 0;
  3543.      
  3544.          if (!cmd)
  3545.              return errno = EINVAL, -1;
  3546.      
  3547.          pipefds[0][0] = pipefds[0][1] = -1;
  3548.          pipefds[1][0] = pipefds[1][1] = -1;
  3549.          pipefds[2][0] = pipefds[2][1] = -1;
  3550.      
  3551.          if (infd && pipe(pipefds[0]) < 0)
  3552.              error = errno;
  3553.          else if (outfd && pipe(pipefds[1]) < 0)
  3554.              error = errno;
  3555.          else if (errfd && pipe(pipefds[2]) < 0)
  3556.              error = errno;
  3557.      
  3558.          if (!error && !(infd && outfd && errfd))
  3559.          {
  3560.              nullfd = open("/dev/null",O_RDWR);
  3561.              if (nullfd < 0)
  3562.                  error = errno;
  3563.          }
  3564.      
  3565.          if (!error)
  3566.          {
  3567.              pid_t pid = spawn_job(0, -1);
  3568.              switch (pid)
  3569.              {
  3570.                  case -1: /* fork failure */
  3571.                      error = errno;
  3572.                      break;
  3573.      
  3574.                  case 0: /* child proc */
  3575.      
  3576.                      dup2(infd ? pipefds[0][0] : nullfd, 0);
  3577.                      dup2(outfd ? pipefds[1][1] : nullfd, 1);
  3578.                      dup2(errfd ? pipefds[2][1] : nullfd, 2);
  3579.                      closeall(3);
  3580.      
  3581.                      execl("/bin/sh","sh","-c",cmd,(char*)NULL);
  3582.      
  3583.                      _exit(127);
  3584.      
  3585.                  default: /* parent proc */
  3586.      
  3587.                      close(nullfd);
  3588.                      if (infd)
  3589.                          close(pipefds[0][0]), *infd = pipefds[0][1];
  3590.                      if (outfd)
  3591.                          close(pipefds[1][1]), *outfd = pipefds[1][0];
  3592.                      if (errfd)
  3593.                          close(pipefds[2][1]), *errfd = pipefds[2][0];
  3594.      
  3595.                      return pid;
  3596.              }
  3597.          }
  3598.      
  3599.          /* only reached if error */
  3600.      
  3601.          {
  3602.              int i,j;
  3603.              for (i = 0; i < 3; ++i)
  3604.                  for (j = 0; j < 2; ++j)
  3605.                      if (pipefds[i][j] >= 0)
  3606.                          close(pipefds[i][j]);
  3607.          }
  3608.      
  3609.          if (nullfd >= 0)
  3610.              close(nullfd);
  3611.      
  3612.          return errno = error, (pid_t) -1;
  3613.      }
  3614.      
  3615.      
  3616.      /*--------------------------------------------------------------------*/
  3617.      /* This bit is a somewhat trivial example of using the above.         */
  3618.      
  3619.      pid_t bgjob = -1;
  3620.      volatile int signo = 0;
  3621.      
  3622.      #ifndef WCOREDUMP
  3623.       /* If WCOREDUMP is missing, you might want to supply a correct
  3624.        * definition for your platform (this is usually (status & 0x80) but
  3625.        * not always) or punt (as in this example) by assuming no core dumps.
  3626.        */
  3627.      # define WCOREDUMP(status) (0)
  3628.      #endif
  3629.      
  3630.      int check_children()
  3631.      {
  3632.          pid_t pid;
  3633.          int status;
  3634.          int count = 0;
  3635.      
  3636.          while ((pid = waitpid(-1, &status, WNOHANG | WUNTRACED)) > 0)
  3637.          {
  3638.              if (pid == bgjob && !WIFSTOPPED(status))
  3639.                  bgjob = -1;
  3640.      
  3641.              ++count;
  3642.      
  3643.              if (WIFEXITED(status))
  3644.                  fprintf(stderr,"Process %ld exited with return code %d\n",
  3645.                          (long)pid, WEXITSTATUS(status));
  3646.              else if (WIFSIGNALED(status))
  3647.                  fprintf(stderr,"Process %ld killed by signal %d%s\n",
  3648.                          (long)pid, WTERMSIG(status),
  3649.                          WCOREDUMP(status) ? " (core dumped)" : "");
  3650.              else if (WIFSTOPPED(status))
  3651.                  fprintf(stderr,"Process %ld stopped by signal %d\n",
  3652.                          (long)pid, WSTOPSIG(status));
  3653.              else
  3654.                  fprintf(stderr,"Unexpected status - pid=%ld, status=0x%x\n",
  3655.                          (long)pid, status);
  3656.          }
  3657.      
  3658.          return count;
  3659.      }
  3660.      
  3661.      
  3662.      void sighandler(int sig)
  3663.      {
  3664.          if (sig != SIGCHLD)
  3665.              signo = sig;
  3666.      }
  3667.      
  3668.      
  3669.      int main()
  3670.      {
  3671.          struct sigaction act;
  3672.          int sigcount = 0;
  3673.      
  3674.          act.sa_handler = sighandler;
  3675.          act.sa_flags = 0;
  3676.          sigemptyset(&act.sa_mask);
  3677.          sigaction(SIGINT,&act,NULL);
  3678.          sigaction(SIGQUIT,&act,NULL);
  3679.          sigaction(SIGTERM,&act,NULL);
  3680.          sigaction(SIGTSTP,&act,NULL);
  3681.          sigaction(SIGCHLD,&act,NULL);
  3682.      
  3683.          fprintf(stderr,"Starting background job 'sleep 60'\n");
  3684.          bgjob = spawn_background_command("sleep 60", NULL, NULL, NULL);
  3685.          if (bgjob < 0)
  3686.          {
  3687.              perror("spawn_background_command");
  3688.              exit(1);
  3689.          }
  3690.          fprintf(stderr,"Background job started with id %ld\n", (long)bgjob);
  3691.          while (bgjob >= 0)
  3692.          {
  3693.              if (signo)
  3694.              {
  3695.                  fprintf(stderr,"Signal %d caught\n", signo);
  3696.                  if (sigcount++)
  3697.                      kill_job(bgjob, SIGKILL);
  3698.                  else
  3699.                  {
  3700.                      kill_job(bgjob, SIGTERM);
  3701.                      kill_job(bgjob, SIGCONT);
  3702.                  }
  3703.              }
  3704.      
  3705.              if (!check_children())
  3706.                  pause();
  3707.          }
  3708.      
  3709.          fprintf(stderr,"Done - exiting\n");
  3710.          return 0;
  3711.      }
  3712.  
  3713.  
  3714. ==============================================================================
  3715. -- 
  3716. Andrew.
  3717.