home *** CD-ROM | disk | FTP | other *** search
/ Internet Info 1997 December / Internet_Info_CD-ROM_Walnut_Creek_December_1997.iso / faqs / comp / unix / programmer / faq < prev    next >
Encoding:
Internet Message Format  |  1997-10-07  |  98.1 KB

  1. Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!news-out.internetmci.com!newsfeed.internetmci.com!206.229.87.25!news-peer.sprintlink.net!news.sprintlink.net!Sprint!cpk-news-hub1.bbnplanet.com!news.bbnplanet.com!dispose.news.demon.net!demon!news.demon.co.uk!erlenstar.demon.co.uk!not-for-mail
  2. From: Andrew Gierth <andrew@erlenstar.demon.co.uk>
  3. Newsgroups: comp.unix.programmer,comp.answers,news.answers
  4. Subject: Unix Programming FAQ (v1.21)
  5. Supersedes: <auto-cup-faq-000015-19970908045113@erlenstar.demon.co.uk>
  6. Followup-To: poster
  7. Date: 7 Oct 1997 03:58:44 +0100
  8. Organization: none at all
  9. Approved: news-answers-request@MIT.EDU
  10. Expires: 26 Oct 1997 02:58:44 -0000
  11. Message-ID: <auto-cup-faq-000016-19971007035844@erlenstar.demon.co.uk>
  12. NNTP-Posting-Host: localhost
  13. Summary: This posting contains answers to frequently-asked questions regarding
  14.      programming in the Unix environment.
  15. Keywords: unix faq
  16. X-NNTP-Posting-Host: erlenstar.demon.co.uk [194.222.144.22]
  17. Lines: 2691
  18. Xref: senator-bedfellow.mit.edu comp.unix.programmer:65430 comp.answers:28401 news.answers:113951
  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 Andrew Gierth.
  26. Last-Modified: 1997/08/24 22:15:49
  27. Version: 1.21
  28.  
  29. ==============================================================================
  30.  
  31. About this FAQ
  32. **************
  33.  
  34. $Id: rawfaq.texi,v 1.21 1997/08/24 22:15:49 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 Andrew Gierth. This document may be distributed freely
  66. on Usenet or by email; it may be archived on FTP or WWW sites that mirror
  67. the news.answers archives, provided that all reasonable efforts are made to
  68. ensure that the archive is kept up-to-date.  (This permission may be
  69. withdrawn on an individual basis.) It may not be published in any other
  70. form, whether in print, on the WWW, on CD-ROM, or in any other medium,
  71. 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@iquest.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.  
  92. List of Questions
  93. *****************
  94.  
  95. 1. Process Control
  96.   1.1 Creating new processes: fork()
  97.     1.1.1 What does fork() do?
  98.     1.1.2 What's the difference between fork() and vfork()?
  99.     1.1.3 Why use _exit rather than exit in the child branch of a fork?
  100.   1.2 Environment variables
  101.     1.2.1 How can I get/set an environment variable from a program?
  102.     1.2.2 How can I read the whole environment?
  103.   1.3 How can I sleep for less than a second?
  104.   1.4 How can I get a finer-grained version of alarm()?
  105.   1.5 How can a parent and child process communicate?
  106.   1.6 How do I get rid of zombie processes?
  107.     1.6.1 What is a zombie?
  108.     1.6.2 How do I prevent them from occuring?
  109.   1.7 How do I get my program to act like a daemon?
  110.   1.8 How can I look at process in the system like ps does?
  111.   1.9 Given a pid, how can I tell if it's a running program?
  112.   1.10 What's the return value of system/pclose/waitpid?
  113.   1.11 How do I find out about a process' memory usage?
  114.   1.12 Why do processes never decrease in size?
  115.   1.13 How do I change the name of my program (as seen by 'ps')?
  116.   1.14 How can I find a process' executable file?
  117.     1.14.1 So where do I put my configuration files then?
  118.  
  119. 2. General File handling (including pipes and sockets)
  120.   2.1 How to manage multiple connections?
  121.     2.1.1 How do I use select()?
  122.     2.1.2 How do I use poll()?
  123.     2.1.3 Can I use SysV IPC at the same time as select or poll?
  124.   2.2 How can I tell when the other end of a connection shuts down?
  125.   2.3 Best way to read directories?
  126.   2.4 How can I find out if someone else has a file open?
  127.   2.5 How do I 'lock' a file?
  128.   2.6 How do I find out if a file has been updated by another process?
  129.   2.7 How does the 'du' utility work?
  130.   2.8 How do I find the size of a file?
  131.   2.9 How do I expand '~' in a filename like the shell does?
  132.   2.10 What can I do with named pipes (FIFOs)?
  133.     2.10.1 What is a named pipe?
  134.     2.10.2 How do I create a named pipe?
  135.     2.10.3 How do I use a named pipe?
  136.     2.10.4 Can I use a named pipe across NFS?
  137.     2.10.5 Can multiple processes write to the pipe simultaneously?
  138.     2.10.6 Using named pipes in applications
  139.  
  140. 3. Terminal I/O
  141.   3.1 How can I make my program not echo input?
  142.   3.2 How can I read single characters from the terminal?
  143.   3.3 How can I check and see if a key was pressed?
  144.   3.4 How can I move the cursor around the screen?
  145.   3.5 What are pttys?
  146.   3.6 How to handle a serial port or modem?
  147.  
  148. 4. System Information
  149.   4.1 How can I tell how much memory my system has?
  150.   4.2 How do I check a user's password?
  151.     4.2.1 How do I get a user's password?
  152.     4.2.2 How do I get shadow passwords by uid?
  153.     4.2.3 How do I verify a user's password?
  154.  
  155. 5. Miscellaneous programming
  156.   5.1 How do I compare strings using wildcards?
  157.     5.1.1 How do I compare strings using filename patterns?
  158.     5.1.2 How do I compare strings using regular expressions?
  159.   5.2 What's the best way to send mail from a program?
  160.     5.2.1 The simple method: /bin/mail
  161.     5.2.2 Invoking the MTA directly: /usr/lib/sendmail
  162.       5.2.2.1 Supplying the envelope explicitly
  163.       5.2.2.2 Allowing sendmail to deduce the recipients
  164.  
  165. 6. Use of tools
  166.   6.1 How can I debug the children after a fork?
  167.   6.2 How to build library from other libraries?
  168.   6.3 How to create shared libraries / dlls?
  169.   6.4 Can I replace objects in a shared library?
  170.   6.5 How can I generate a stack dump from within a running program?
  171.  
  172. 1. Process Control
  173. ******************
  174.  
  175. 1.1 Creating new processes: fork()
  176. ==================================
  177.  
  178. 1.1.1 What does fork() do?
  179. --------------------------
  180.  
  181.      #include <sys/types.h>
  182.      #include <unistd.h>
  183.      
  184.      pid_t fork(void);
  185.  
  186. The `fork()' function is used to create a new process from an existing
  187. process.  The new process is called the child process, and the existing
  188. process is called the parent.  You can tell which is which by checking the
  189. return value from `fork()'.  The parent gets the child's pid returned to
  190. him, but the child gets 0 returned to him.  Thus this simple code
  191. illustrate's the basics of it.
  192.  
  193.      pid_t pid;
  194.      
  195.      switch (pid = fork())
  196.      {
  197.      case -1:
  198.          /* Here pid is -1, the fork failed */
  199.          /* Some possible reasons are that you're */
  200.          /* out of process slots or virtual memory */
  201.          perror("The fork failed!");
  202.          break;
  203.      
  204.      case 0:
  205.          /* pid of zero is the child */
  206.          /* Here we're the child...what should we do? */
  207.          /* ... */
  208.          /* but after doing it, we should do something like: */
  209.          _exit(0);
  210.      
  211.      default:
  212.          /* pid greater than zero is parent getting the child's pid */
  213.          printf("Child's pid is %d\n",pid);
  214.      }
  215.  
  216. Of course, one can use `if()... else...' instead of `switch()', but the
  217. above form is a useful idiom.
  218.  
  219. Of help when doing this is knowing just what is and is not inherited by the
  220. child.  This list can vary depending on Unix implementation, so take it
  221. with a grain of salt.  Note that the child gets COPIES of these things, not
  222. the real thing.
  223.  
  224. Inherited by the child from the parent:
  225.  
  226.    * process credentials (real/effective/saved UIDs and GIDs)
  227.  
  228.    * environment
  229.  
  230.    * stack
  231.  
  232.    * memory
  233.  
  234.    * open file descriptors (note that the underlying file positions are
  235.      shared between the parent and child, which can be confusing)
  236.  
  237.    * close-on-exec flags
  238.  
  239.    * signal handling settings
  240.  
  241.    * nice value
  242.  
  243.    * scheduler class
  244.  
  245.    * process group ID
  246.  
  247.    * session ID
  248.  
  249.    * current working directory
  250.  
  251.    * root directory
  252.  
  253.    * file mode creation mask (umask)
  254.  
  255.    * resource limits
  256.  
  257.    * controlling terminal
  258.  
  259. Unique to the child:
  260.  
  261.    * process ID
  262.  
  263.    * different parent process ID
  264.  
  265.    * Own copy of file descriptors and directory streams.
  266.  
  267.    * process, text, data and other memory locks are NOT inherited.
  268.  
  269.    * process times, in the tms struct
  270.  
  271.    * resource utilizations are set to 0
  272.  
  273.    * pending signals initialized to the empty set
  274.  
  275.    * timers created by timer_create not inherited
  276.  
  277.    * asynchronous input or output operations not inherited
  278.  
  279. 1.1.2 What's the difference between fork() and vfork()?
  280. -------------------------------------------------------
  281.  
  282. Some systems have a system call `vfork()', which was originally designed as
  283. a lower-overhead version of `fork()'. Since `fork()' involved copying the
  284. entire address space of the process, and was therefore quite expensive, the
  285. `vfork()' function was introduced (in 3.0BSD).
  286.  
  287. *However*, since `vfork()' was introduced, the implementation of `fork()'
  288. has improved drastically, most notably with the introduction of
  289. 'copy-on-write', where the copying of the process address space is
  290. transparently faked by allowing both processes to refer to the same
  291. physical memory until either of them modify it. This largely removes the
  292. justification for `vfork()'; indeed, a large proportion of systems now lack
  293. the functionality of `vfork()' completely. For compatibility, though, there
  294. may still be a `vfork()' call present, that simply calls `fork()' without
  295. attempting to emulate the `vfork()' semantics.
  296.  
  297. As a result, it is *very* unwise to actually make use of any of the
  298. differences between `fork()' and `vfork()'. Indeed, it is probably unwise
  299. to use `vfork()' at all, unless you know exactly *why* you want to.
  300.  
  301. The basic difference between the two is that when a new process is created
  302. with `vfork()', the parent process is temporarily suspended, and the child
  303. process borrows the parent's address space. This strange state of affairs
  304. continues until the child process either exits, or calls `execve()', at
  305. which point the parent process continues.
  306.  
  307. This means that the child process of a `vfork()' must be *extremely*
  308. careful to avoid unexpectedly modifying variables of the parent process. In
  309. particular, the child process must *not* return from the function
  310. containing the `vfork()' call, and it must *not* call `exit()' (if it needs
  311. to exit, it should use `_exit()'; actually, this is also true for the child
  312. of a normal `fork()').
  313.  
  314. (There are some deviant systems, e.g. SCO OpenServer, that have a `vfork()'
  315. that is distinct from `fork()', but only emulates part of the original
  316. `vfork()' - in this case, it suspends the parent process, but doesn't share
  317. the address space with the child. I have no idea why they thought this
  318. would be useful.)
  319.  
  320. 1.1.3 Why use _exit rather than exit in the child branch of a fork?
  321. -------------------------------------------------------------------
  322.  
  323. There are a few differences between `exit()' and `_exit()' that become
  324. significant when `fork()', and especially `vfork()', is used.
  325.  
  326. The basic difference between `exit()' and `_exit()' is that the former
  327. performs clean-up related to user-mode constructs in the library, and calls
  328. user-supplied cleanup functions, whereas the latter performs only the
  329. kernel cleanup for the process.
  330.  
  331. In the child branch of a `fork()', it is normally incorrect to use
  332. `exit()', because that can lead to stdio buffers being flushed twice, and
  333. temporary files being unexpectedly removed. In C++ code the situation is
  334. worse, because destructors for static objects may be run incorrectly.
  335. (There are some unusual cases, like daemons, where the *parent* should call
  336. `_exit()' rather than the child; the basic rule, applicable in the
  337. overwhelming majority of cases, is that `exit()' should be called only once
  338. for each entry into `main'.)
  339.  
  340. In the child branch of a `vfork()', the use of `exit()' is even more
  341. dangerous, since it will affect the state of the *parent* process.
  342.  
  343. 1.2 Environment variables
  344. =========================
  345.  
  346. 1.2.1 How can I get/set an environment variable from a program?
  347. ---------------------------------------------------------------
  348.  
  349. Getting the value of an environment variable is done by using `getenv()'.
  350.  
  351.      #include <stdlib.h>
  352.      
  353.      char *getenv(const char *name);
  354.  
  355. Setting the value of an environment variable is done by using `putenv()'.
  356.  
  357.      #include <stdlib.h>
  358.      
  359.      int putenv(char *string);
  360.  
  361. The string passed to putenv must *not* be freed or made invalid, since a
  362. pointer to it is kept by `putenv()'. This means that it must either be a
  363. static buffer or allocated off the heap. The string can be freed if the
  364. environment variable is redefined or deleted via another call to `putenv()'.
  365.  
  366. Remember that environment variables are inherited; each process has a
  367. separate copy of the environment. As a result, you can't change the value
  368. of an environment variable in another process, such as the shell.
  369.  
  370. Suppose you wanted to get the value for the `TERM' environment variable.
  371. You would use this code:
  372.  
  373.      char *envvar;
  374.      
  375.      envvar=getenv("TERM");
  376.      
  377.      printf("The value for the environment variable TERM is "
  378.      if(envvar)
  379.      {
  380.          printf("%s\n",envvar);
  381.      }
  382.      else
  383.      {
  384.          printf("not set.\n");
  385.      }
  386.  
  387. Now suppose you wanted to create a new environment variable called `MYVAR',
  388. with a value of `MYVAL'.  This is how you'd do it.
  389.  
  390.      static char envbuf[256];
  391.      
  392.      sprintf(envbuf,"MYVAR=%s","MYVAL");
  393.      
  394.      if(putenv(envbuf))
  395.      {
  396.          printf("Sorry, putenv() couldn't find the memory for %s\n",envbuf);
  397.          /* Might exit() or something here if you can't live without it */
  398.      }
  399.  
  400. 1.2.2 How can I read the whole environment?
  401. -------------------------------------------
  402.  
  403. If you don't know the names of the environment variables, then the
  404. `getenv()' function isn't much use. In this case, you have to dig deeper
  405. into how the environment is stored.
  406.  
  407. A global variable, `environ', holds a pointer to an array of pointers to
  408. environment strings, each string in the form `"NAME=value"'. A `NULL'
  409. pointer is used to mark the end of the array. Here's a trivial program to
  410. print the current environment (like `printenv'):
  411.  
  412.      #include <stdio.h>
  413.      
  414.      extern char **environ;
  415.      
  416.      int main()
  417.      {
  418.          char **ep = environ;
  419.          char *p;
  420.          while ((p = *ep++))
  421.              printf("%s\n", p);
  422.          return 0;
  423.      }
  424.  
  425. In general, the `environ' variable is also passed as the third, optional,
  426. parameter to `main()'; that is, the above could have been written:
  427.  
  428.      #include <stdio.h>
  429.      
  430.      int main(int argc, char **argv, char **envp)
  431.      {
  432.          char *p;
  433.          while ((p = *envp++))
  434.              printf("%s\n", p);
  435.          return 0;
  436.      }
  437.  
  438. However, while pretty universally supported, this method isn't actually
  439. defined by the POSIX standards. (It's also less useful, in general.)
  440.  
  441. 1.3 How can I sleep for less than a second?
  442. ===========================================
  443.  
  444. The `sleep()' function, which is available on all Unixes, only allows for a
  445. duration specified in seconds. If you want finer granularity, then you need
  446. to look for alternatives:
  447.  
  448.    * Many systems have a function `usleep()'
  449.  
  450.    * You can use `select()' or `poll()', specifying no file descriptors to
  451.      test; a common technique is to write a `usleep()' function based on
  452.      either of these (see the comp.unix.questions FAQ for some examples)
  453.  
  454.    * If your system has itimers (most do), you can roll your own `usleep()'
  455.      using them (see the BSD sources for `usleep()' for how to do this)
  456.  
  457.    * If you have POSIX realtime, there is a `nanosleep()' function
  458.  
  459. Whichever route you choose, it is important to realise that you may be
  460. constrained by the timer resolution of the system (some systems allow very
  461. short time intervals to be specified, others have a resolution of, say,
  462. 10ms and will round all timings to that). Also, as for `sleep()', the delay
  463. you specify is only a *minimum* value; after the specified period elapses,
  464. there will be an indeterminate delay before your process next gets
  465. scheduled.
  466.  
  467. 1.4 How can I get a finer-grained version of alarm()?
  468. =====================================================
  469.  
  470. Modern Unixes tend to implement alarms using the `setitimer()' function,
  471. which has a higher resolution and more options than the simple `alarm()'
  472. function. One should generally assume that `alarm()' and
  473. `setitimer(ITIMER_REAL)' may be the same underlying timer, and accessing it
  474. both ways may cause confusion.
  475.  
  476. Itimers can be used to implement either one-shot or repeating signals;
  477. also, there are generally 3 separate timers available:
  478.  
  479. `ITIMER_REAL'
  480.      counts real (wall clock) time, and sends the `SIGALRM' signal
  481.  
  482. `ITIMER_VIRTUAL'
  483.      counts process virtual (user CPU) time, and sends the `SIGVTALRM'
  484.      signal
  485.  
  486. `ITIMER_PROF'
  487.      counts user and system CPU time, and sends the `SIGPROF' signal; it is
  488.      intended for interpreters to use for profiling.
  489.  
  490. Itimers, however, are not part of many of the standards, despite having
  491. been present since 4.2BSD. The POSIX realtime extensions define a similar,
  492. but different, function: `settimer()'. There are also functions defined to
  493. query the resolution of POSIX timers.
  494.  
  495. 1.5 How can a parent and child process communicate?
  496. ===================================================
  497.  
  498. A parent and child can communicate through any of the normal inter-process
  499. communication schemes (pipes, sockets, message queues, shared memory), but
  500. also have some special ways to communicate that take advantage of their
  501. relationship as a parent and child.
  502.  
  503. One of the most obvious is that the parent can get the exit status of the
  504. child.
  505.  
  506. Since the child inherits file descriptors from its parent, the parent can
  507. open both ends of a pipe, fork, then the parent close one end and the child
  508. close the other end of the pipe.  This is what happens when you call the
  509. `popen()' routine to run another program from within yours, i.e. you can
  510. write the the file descriptor returned from popen() and the child process
  511. sees it as its stdin, and you can read from the file descriptor and see
  512. what the program wrote to it's stdout.
  513.  
  514. Also, the child process inherits memory segments mmapped anonymously (or by
  515. mmapping the special file `/dev/zero') by the parent; these shared memory
  516. segments are not accessible from unrelated processes.
  517.  
  518. 1.6 How do I get rid of zombie processes?
  519. =========================================
  520.  
  521. 1.6.1 What is a zombie?
  522. -----------------------
  523.  
  524. When a program forks and the child finishes before the parent, the kernel
  525. still keeps some of its information about the child in case the parent
  526. might need it - for example, the parent may need to check the child's exit
  527. status. To be able to get this information, the parent calls `wait()'; when
  528. this happens, the kernel can discard the information.
  529.  
  530. In the interval between the child terminating and the parent calling
  531. `wait()', the child is said to be a "zombie" (if you do 'ps', the child
  532. will have a 'Z' in its status field to indicate this). Even though it's not
  533. running, it's still taking up an entry in the process table.  (It consumes
  534. no other resources, but some utilities may show bogus figures for e.g. CPU
  535. usage; this is because some parts of the process table entry have been
  536. overlaid by accounting info to save space.)
  537.  
  538. This is not good, as the process table has a fixed number of entries and it
  539. is possible for the system to run out of them. Even if the system doesn't
  540. run out, there is a limit on the number of processes each user can run,
  541. which is usually smaller than the system's limit. This is one of the
  542. reasons why you should always check if `fork()' failed, by the way!
  543.  
  544. If the parent terminates without calling wait(), the child is "adopted" by
  545. `init', which handles the work necessary to cleanup after the child. (This
  546. is a special system program with process ID 1 - it's actually the first
  547. program to run after the system boots up).
  548.  
  549. 1.6.2 How do I prevent them from occuring?
  550. ------------------------------------------
  551.  
  552. You need to ensure that your parent process calls `wait()' (or `waitpid()',
  553. `wait3()', etc.) for every child process that terminates; or, on some
  554. systems, you can instruct the system that you are uninterested in child
  555. exit states.
  556.  
  557. Another approach is to `fork()' *twice*, and have the immediate child
  558. process exit straight away. This causes the grandchild process to be
  559. orphaned, so the init process is responsible for cleaning it up. For code
  560. to do this, see the function `fork2()' in the examples section.
  561.  
  562. To ignore child exit states, you need to do the following (check your
  563. system's manpages to see if this works):
  564.  
  565.          struct sigaction sa;
  566.          sa.sa_handler = SIG_IGN;
  567.      #ifdef SA_NOCLDWAIT
  568.          sa.sa_flags = SA_NOCLDWAIT;
  569.      #else
  570.          sa.sa_flags = 0;
  571.      #endif
  572.          sigemptyset(&sa.sa_mask);
  573.          sigaction(SIGCHLD, &sa, NULL);
  574.  
  575. If this is successful, then the `wait()' functions are prevented from
  576. working; if any of them are called, they will wait until *all* child
  577. processes have terminated, then return failure with `errno == ECHILD'.
  578.  
  579. The other technique is to catch the SIGCHLD signal, and have the signal
  580. handler call `waitpid()' or `wait3()'. See the examples section for a
  581. complete program.
  582.  
  583. 1.7 How do I get my program to act like a daemon?
  584. =================================================
  585.  
  586. A "daemon" process is usually defined as a background process that does not
  587. belong to a terminal session. Many system services are performed by
  588. daemons; network services, printing etc.
  589.  
  590. Simply invoking a program in the background isn't really adequate for these
  591. long-running programs; that does not correctly detach the process from the
  592. terminal session that started it. Also, the conventional way of starting
  593. daemons is simply to issue the command manually or from an rc script; the
  594. daemon is expected to put *itself* into the background.
  595.  
  596. Here are the steps to become a daemon:
  597.  
  598.   1. `fork()' so the parent can exit, this returns control to the command
  599.      line or shell invoking your program.  This step is required so that
  600.      the new process is guaranteed not to be a process group leader. The
  601.      next step, `setsid()', fails if you're a process group leader.
  602.  
  603.   2. `setsid()' to become a process group and session group leader. Since a
  604.      controlling terminal is associated with a session, and this new
  605.      session has not yet acquired a controlling terminal our process now
  606.      has no controlling terminal, which is a Good Thing for daemons.
  607.  
  608.   3. `fork()' again so the parent, (the session group leader), can exit.
  609.      This means that we, as a non-session group leader, can never regain a
  610.      controlling terminal.
  611.  
  612.   4. `chdir("/")' to ensure that our process doesn't keep any directory in
  613.      use. Failure to do this could make it so that an administrator
  614.      couldn't unmount a filesystem, because it was our current directory.
  615.  
  616.      [Equivalently, we could change to any directory containing files
  617.      important to the daemon's operation.]
  618.  
  619.   5. `umask(0)' so that we have complete control over the permissions of
  620.      anything we write. We don't know what umask we may have inherited.
  621.  
  622.      [This step is optional]
  623.  
  624.   6. `close()' fds 0, 1, and 2. This releases the standard in, out, and
  625.      error we inherited from our parent process. We have no way of knowing
  626.      where these fds might have been redirected to. Note that many daemons
  627.      use `sysconf()' to determine the limit `_SC_OPEN_MAX'.  `_SC_OPEN_MAX'
  628.      tells you the maximun open files/process. Then in a loop, the daemon
  629.      can close all possible file descriptors. You have to decide if you
  630.      need to do this or not.  If you think that there might be
  631.      file-descriptors open you should close them, since there's a limit on
  632.      number of concurrent file descriptors.
  633.  
  634.   7. Establish new open descriptors for stdin, stdout and stderr. Even if
  635.      you don't plan to use them, it is still a good idea to have them open.
  636.      The precise handling of these is a matter of taste; if you have a
  637.      logfile, for example, you might wish to open it as stdout or stderr,
  638.      and open `/dev/null' as stdin; alternatively, you could open
  639.      `/dev/console' as stderr and/or stdout, and `/dev/null' as stdin, or
  640.      any other combination that makes sense for your particular daemon.
  641.  
  642. Almost none of this is necessary (or advisable) if your daemon is being
  643. started by `inetd'. In that case, stdin, stdout and stderr are all set up
  644. for you to refer to the network connection, and the `fork()'s and session
  645. manipulation should *not* be done (to avoid confusing `inetd'). Only the
  646. `chdir()' and `umask()' steps remain as useful.
  647.  
  648. 1.8 How can I look at process in the system like ps does?
  649. =========================================================
  650.  
  651. You really *don't* want to do this.
  652.  
  653. The most portable way, by far, is to do `popen(pscmd, "r")' and parse the
  654. output. (pscmd should be something like `"ps -ef"' on SysV systems; on BSD
  655. systems there are many possible display options: choose one.)
  656.  
  657. In the examples section, there are two complete versions of this; one for
  658. SunOS 4, which requires root permission to run and uses the `kvm_*'
  659. routines to read the information from kernel data structures; and another
  660. for SVR4 systems (including SunOS 5), which uses the `/proc' filesystem.
  661.  
  662. It's even easier on systems with an SVR4.2-style `/proc'; just read a
  663. psinfo_t structure from the file `/proc/PID/psinfo' for each PID of
  664. interest. However, this method, while probably the cleanest, is also
  665. perhaps the least well-supported. (On FreeBSD's /proc, you read a
  666. semi-undocumented printable string from `/proc/PID/status'; Linux has
  667. something similar.)
  668.  
  669. 1.9 Given a pid, how can I tell if it's a running program?
  670. ==========================================================
  671.  
  672. Use `kill()' with 0 for the signal number.
  673.  
  674. There are four possible results from this call:
  675.  
  676.    * `kill()' returns 0
  677.  
  678.         - this implies that a process exists with the given PID, and the
  679.           system would allow you to send signals to it. It is
  680.           system-dependent whether the process could be a zombie.
  681.  
  682.    * `kill()' returns -1, `errno == ESRCH'
  683.  
  684.         - either no process exists with the given PID, or security
  685.           enhancements are causing the system to deny its existence. (On
  686.           some systems, the process could be a zombie.)
  687.  
  688.    * `kill()' returns -1, `errno == EPERM'
  689.  
  690.         - the system would not allow you to kill the specified process.
  691.           This means that either the process exists (again, it could be a
  692.           zombie) or draconian security enhancements are present (e.g. your
  693.           process is not allowed to send signals to *anybody*).
  694.  
  695.    * `kill()' returns -1, with some other value of `errno'
  696.  
  697.         - you are in trouble!
  698.  
  699. The most-used technique is to assume that success or failure with `EPERM'
  700. implies that the process exists, and any other error implies that it
  701. doesn't.
  702.  
  703. 1.10 What's the return value of system/pclose/waitpid?
  704. ======================================================
  705.  
  706.      The return value of `system()', `pclose()', or `waitpid()' doesn't
  707.      seem to be the exit value of my process...  or the exit value is
  708.      shifted left 8 bits... what's the deal?
  709.  
  710. The man page is right, and so are you!  If you read the man page for
  711. `waitpid()' you'll find that the return code for the process is encoded.
  712. The value returned by the process is normally in the top 16 bits, and the
  713. rest is used for other things.  You can't rely on this though, not if you
  714. want to be portable, so the suggestion is that you use the macros provided.
  715. These are usually documented under `wait()' or `wstat'.
  716.  
  717. Macros defined for the purpose (in `<sys/wait.h>') include (stat is the
  718. value returned by `waitpid()'):
  719.  
  720. `WIFEXITED(stat)'
  721.      Non zero if child exited normally.
  722.  
  723. `WEXITSTATUS(stat)'
  724.      exit code returned by child
  725.  
  726. `WIFSIGNALED(stat)'
  727.      Non-zero if child was terminated by a signal
  728.  
  729. `WTERMSIG(stat)'
  730.      signal number that terminated child
  731.  
  732. `WIFSTOPPED(stat)'
  733.      non-zero if child is stopped
  734.  
  735. `WSTOPSIG(stat)'
  736.      number of signal that stopped child
  737.  
  738. `WIFCONTINUED(stat)'
  739.      non-zero if status was for continued child
  740.  
  741. `WCOREDUMP(stat)'
  742.      If WIFSIGNALED(stat) non-zero this is non-zero if core dumped
  743.  
  744. 1.11 How do I find out about a process' memory usage?
  745. =====================================================
  746.  
  747. Look at `getrusage()', if available.
  748.  
  749. 1.12 Why do processes never decrease in size?
  750. =============================================
  751.  
  752. When you free memory back to the heap with free(), on almost all systems
  753. that *doesn't* reduce the memory usage of your program. The memory 'free'd
  754. is still part of the process' address space, and will be used to satisfy
  755. future `malloc()' requests.
  756.  
  757. If you really need to free memory back to the system, look at using
  758. `mmap()' to allocate private anonymous mappings. When these are unmapped,
  759. the memory really is released back to the system.
  760.  
  761. Of course, if your program increases in size when you think it shouldn't,
  762. you may have a 'memory leak' - a bug in your program that results in unused
  763. memory not being freed.
  764.  
  765. 1.13 How do I change the name of my program (as seen by 'ps')?
  766. ==============================================================
  767.  
  768. On BSDish systems, the `ps' program actually looks into the address space
  769. of the running process to find the current `argv[]', and displays that.
  770. That enables a program to change its 'name' simply by modifying `argv[]'.
  771.  
  772. On SysVish systems, the command name and usually the first 80 bytes of the
  773. parameters are stored in the process' u-area, and so can't be directly
  774. modified. There may be a system call to change this (unlikely), but
  775. otherwise the only way is to perform an `exec()', or write into kernel
  776. memory (dangerous, and only possible if running as root).
  777.  
  778. Some systems (notably Solaris) may have two separate versions of `ps', one
  779. in `/usr/bin/ps' with SysV behaviour, and one in `/usr/ucb/ps' with BSD
  780. behaviour. On these systems, if you change `argv[]', then the BSD version
  781. of `ps' will reflect the change, and the SysV version won't.
  782.  
  783. Check to see if your system has a function `setproctitle()'.
  784.  
  785. 1.14 How can I find a process' executable file?
  786. ===============================================
  787.  
  788. This would be a good candidate for a list of "Frequently Unanswered
  789. Questions", because the fact of asking the question usually means that the
  790. design of the program is flawed :-)
  791.  
  792. You can make a "best guess" by looking at the value of `argv[0]'. If this
  793. contains a `/', then it is probably the absolute or relative (to the
  794. current directory at program start) path of the executable. If it does not,
  795. then you can mimic the shell's search of the `PATH' variable, looking for
  796. the program. However, success is not guaranteed, since it is possible to
  797. invoke programs with arbitrary values of `argv[0]', and in any case the
  798. executable may have been renamed or deleted since it was started.
  799.  
  800. The most common reason people ask this question is in order to locate
  801. configuration files with their program. This is considered to be bad form;
  802. directories containing executables should contain *nothing* except
  803. executables, and administrative requirements often make it desirable for
  804. configuration files to be located on different filesystems to executables.
  805.  
  806. A less common, but more legitimate, reason to do this is to allow the
  807. program to call `exec()' *on itself*; this is a method used (e.g. by some
  808. versions of `sendmail') to completely reinitialise the process (e.g. if a
  809. daemon receives a `SIGHUP').
  810.  
  811. 1.14.1 So where do I put my configuration files then?
  812. -----------------------------------------------------
  813.  
  814. The correct directory for this usually depends on the particular flavour of
  815. Unix you're using; `/var/opt/PACKAGE', `/usr/local/lib', `/usr/local/etc',
  816. or any of several other possibilities.  User-specific configuration files
  817. are usually hidden 'dotfiles' under `$HOME' (e.g. `$HOME/.exrc').
  818.  
  819. From the point of view of a package that is expected to be usable across a
  820. range of systems, this usually implies that the location of any sitewide
  821. configuration files will be a compiled-in default, possibly using a -prefix
  822. option on a configure script (Autoconf scripts do this). You might wish to
  823. allow this to be overridden at runtime by an environment variable. (If
  824. you're not using a configure script, then put the default in the Makefile
  825. as a -D option on compiles, or put it in a `config.h' header file, or
  826. something similar.)
  827.  
  828. User-specific configuration should be either a single dotfile under
  829. `$HOME', or, if you need multiple files, a dot-subdirectory.  (Files or
  830. directories whose names start with a dot are omitted from directory
  831. listings by default.) Avoid creating multiple entries under `$HOME',
  832. because this can get very cluttered. Again, you can allow the user to
  833. override this location with an environment variable. Programs should always
  834. behave sensibly if they fail to find any per-user configuration.
  835.  
  836. 2. General File handling (including pipes and sockets)
  837. ******************************************************
  838.  
  839. See also the Sockets FAQ, available at:
  840.  
  841. `http://kipper.york.ac.uk/~vic/sock-faq/'
  842.  
  843. `ftp://rtfm.mit.edu/pub/usenet/news.answers/unix-faq/socket'
  844.  
  845. 2.1 How to manage multiple connections?
  846. =======================================
  847.  
  848.      I have to monitor more than one (fd/connection/stream) at a time. How
  849.      do I manage all of them?
  850.  
  851. Use `select()' or `poll()'.
  852.  
  853. Note: `select()' was introduced in BSD, whereas `poll()' is an artifact of
  854. SysV STREAMS. As such, there are portability issues; pure BSD systems may
  855. still lack `poll()', whereas some older SVR3 systems may not have
  856. `select()'. SVR4 added `select()', and the Posix.1g standard defines both.
  857.  
  858. `select()' and `poll()' essentially do the same thing, just differently.
  859. Both of them examine a set of file descriptors to see if specific events
  860. are pending on any, and then optionally wait for a specified time for an
  861. event to happen.
  862.  
  863. [Important note: neither `select()' nor `poll()' do anything useful when
  864. applied to plain files; they are useful for sockets, pipes, ptys, ttys &
  865. possibly other character devices, but this is system-dependent.]
  866.  
  867. There the similarity ends....
  868.  
  869. 2.1.1 How do I use select()?
  870. ----------------------------
  871.  
  872. The interface to `select()' is primarily based on the concept of an
  873. `fd_set', which is a set of FDs (usually implemented as a bit-vector). In
  874. times past, it was common to assume that FDs were smaller than 32, and just
  875. use an int to store the set, but these days, one usually has more FDs
  876. available, so it is important to use the standard macros for manipulating
  877. fd_sets:
  878.  
  879.      fd_set set;
  880.      FD_ZERO(&set);    /* empties the set */
  881.      FD_SET(fd,&set)   /* adds FD to the set */
  882.      FD_CLR(fd,&set);  /* removes FD from the set */
  883.      FD_ISSET(fd,&set)  /* true if FD is in the set */
  884.  
  885. In most cases, it is the system's responsibility to ensure that fdsets can
  886. handle the whole range of file descriptors, but in some cases you may have
  887. to predefine the `FD_SETSIZE' macro.  *This is system-dependent*; check
  888. your `select()' manpage. Also, some systems have problems handling more
  889. than 1024 file descriptors in `select()'.
  890.  
  891. The basic interface to select is simple:
  892.  
  893.      int select(int nfds, fd_set *readset,
  894.                           fd_set *writeset,
  895.                           fd_set *exceptset, struct timeval *timeout);
  896.  
  897. where
  898.  
  899. `nfds'
  900.      the number of FDs to examine; this must be greater than the largest FD
  901.      in any of the fdsets, *NOT* the actual number of FDs specified
  902.  
  903. `readset'
  904.      the set of FDs to examine for readability
  905.  
  906. `writeset'
  907.      the set of FDs to examine for writability
  908.  
  909. `exceptfds'
  910.      the set of FDs to examine for exceptional status (note: errors are
  911.      *NOT* exceptional statuses)
  912.  
  913. `timeout'
  914.      NULL for infinite timeout, or points to a timeval specifying the
  915.      maximum wait time (if `tv_sec' and `tv_usec' both == 0, then the
  916.      status of the FDs is polled, but the call never blocks)
  917.  
  918. The call returns the number of 'ready' FDs found, and the three fdsets are
  919. modified in-place, with only the ready FDs left in the sets. Use the
  920. `FD_ISSET' macro to test the returned sets.
  921.  
  922. Here's a simple example of testing a single FD for readability:
  923.  
  924.      int isready(int fd)
  925.      {
  926.          int rc;
  927.          fd_set fds;
  928.          struct timeval tv;
  929.      
  930.          FD_ZERO(&fds);
  931.          FD_SET(fd,&fds);
  932.          tv.tv_sec = tv.tv_usec = 0;
  933.      
  934.          rc = select(fd+1, &fds, NULL, NULL, &tv);
  935.          if (rc < 0)
  936.            return -1;
  937.      
  938.          return FD_ISSET(fd,&fds) ? 1 : 0;
  939.      }
  940.  
  941. Note that we can pass `NULL' for fdsets that we aren't interested in
  942. testing.
  943.  
  944. 2.1.2 How do I use poll()?
  945. --------------------------
  946.  
  947. Poll accepts a pointer to a list of `struct pollfd', in which the
  948. descriptors and the events you wish to poll for are stored. The events are
  949. specified via a bitwise mask in the events field of the structure.  The
  950. instance of the structure will later be filled in and returned to you with
  951. any events which occured. Macros defined by `poll.h' on SVR4 (probably
  952. older versions as well), are used to specify the events in the field. A
  953. timeout may be specified in milliseconds, only the type provided is an
  954. integer which is quite perplexing. A timeout of 0 causes `poll()' to return
  955. immediately, a value of -1 will suspend poll till an event is found to be
  956. true.
  957.  
  958.      struct pollfd {
  959.          int fd;        /* The descriptor. */
  960.          short events;  /* The event(s) is/are specified here. */
  961.          short revents; /* Events found are returned here. */
  962.      };
  963.  
  964. Alot like select, the return value if positive reflects how many
  965. descriptors were found to satisfy the events requested. A zero return value
  966. is returned if the timeout period is reached before any of the events
  967. specified have occured. A negative value should immediately be followed by
  968. a check of errno, since it signifies an error.
  969.  
  970. If no events are found, revent is cleared, so there's no need for you to do
  971. this yourself.
  972.  
  973. The returned events are tested to contain the event.
  974.  
  975. Here's an example:
  976.  
  977.      /* Poll on two descriptors for Normal data, or High priority data.
  978.         If any found call function handle() with appropriate descriptor
  979.         and priority. Dont timeout, only giveup if error, or one of the
  980.         descriptors hangs up. */
  981.      
  982.      #include <stdlib.h>
  983.      #include <stdio.h>
  984.      
  985.      #include <sys/types.h>
  986.      #include <stropts.h>
  987.      #include <poll.h>
  988.      
  989.      #include <unistd.h>
  990.      #include <errno.h>
  991.      #include <string.h>
  992.      
  993.      #define NORMAL_DATA 1
  994.      #define HIPRI_DATA 2
  995.      
  996.      int poll_two_normal(int fd1,int fd2)
  997.      {
  998.          struct pollfd poll_list[2];
  999.          int retval;
  1000.      
  1001.          poll_list[0].fd = fd1;
  1002.          poll_list[1].fd = fd2;
  1003.          poll_list[0].events = POLLIN|POLLPRI;
  1004.          poll_list[1].events = POLLIN|POLLPRI;
  1005.      
  1006.          while(1)
  1007.          {
  1008.              retval = poll(poll_list,(unsigned long)2,-1);
  1009.              /* Retval will always be greater than 0 or -1 in this case.
  1010.                 Since we're doing it while blocking */
  1011.      
  1012.              if(retval < 0)
  1013.              {
  1014.                  fprintf(stderr,"Error while polling: %s\n",strerror(errno));
  1015.                  return -1;
  1016.              }
  1017.      
  1018.              if(((poll_list[0].revents&POLLHUP) == POLLHUP) ||
  1019.                 ((poll_list[0].revents&POLLERR) == POLLERR) ||
  1020.                 ((poll_list[0].revents&POLLNVAL) == POLLNVAL) ||
  1021.                 ((poll_list[1].revents&POLLHUP) == POLLHUP) ||
  1022.                 ((poll_list[1].revents&POLLERR) == POLLERR) ||
  1023.                 ((poll_list[1].revents&POLLNVAL) == POLLNVAL))
  1024.                return 0;
  1025.      
  1026.              if((poll_list[0].revents&POLLIN) == POLLIN)
  1027.                handle(poll_list[0].fd,NORMAL_DATA);
  1028.              if((poll_list[0].revents&POLLPRI) == POLLPRI)
  1029.                handle(poll_list[0].fd,HIPRI_DATA);
  1030.              if((poll_list[1].revents&POLLIN) == POLLIN)
  1031.                handle(poll_list[1].fd,NORMAL_DATA);
  1032.              if((poll_list[1].revents&POLLPRI) == POLLPRI)
  1033.                handle(poll_list[1].fd,HIPRI_DATA);
  1034.          }
  1035.      }
  1036.  
  1037. 2.1.3 Can I use SysV IPC at the same time as select or poll?
  1038. ------------------------------------------------------------
  1039.  
  1040. *No.* (Except on AIX, which has an incredibly ugly kluge to allow this.)
  1041.  
  1042. In general, trying to combine the use of `select()' or `poll()' with using
  1043. SysV message queues is troublesome. SysV IPC objects are not handled by
  1044. file descriptors, so they can't be passed to `select()' or `poll()'. There
  1045. are a number of workarounds, of varying degrees of ugliness:
  1046.  
  1047.    - Abandon SysV IPC completely :-)
  1048.  
  1049.    - `fork()', and have the child process handle the SysV IPC,
  1050.      communicating with the parent process by a pipe or socket, which the
  1051.      parent process can `select()' on.
  1052.  
  1053.    - As above, but have the child process do the `select()', and
  1054.      communicate with the parent by message queue.
  1055.  
  1056.    - Arrange for the process that sends messages to you to send a signal
  1057.      after each message. *Warning:* handling this right is non-trivial;
  1058.      it's very easy to write code that can potentially lose messages or
  1059.      deadlock using this method.
  1060.  
  1061. (Other methods exist.)
  1062.  
  1063. 2.2 How can I tell when the other end of a connection shuts down?
  1064. =================================================================
  1065.  
  1066. If you try to read from a pipe, socket, FIFO etc. when the writing end of
  1067. the connection has been closed, you get an end-of-file indication (`read()'
  1068. returns 0 bytes read). If you try and write to a pipe, socket etc. when the
  1069. reading end has closed, then a `SIGPIPE' signal will be delivered to the
  1070. process, killing it unless the signal is caught. (If you ignore or block
  1071. the signal, the `write()' call fails with `EPIPE'.)
  1072.  
  1073. 2.3 Best way to read directories?
  1074. =================================
  1075.  
  1076. While historically there have been several different interfaces for this,
  1077. the only one that really matters these days the the Posix.1 standard
  1078. `<dirent.h>' functions.
  1079.  
  1080. The function `opendir()' opens a specified directory; `readdir()' reads
  1081. directory entries from it in a standardised format; `closedir()' does the
  1082. obvious. Also provided are `rewinddir()', `telldir()' and `seekdir()' which
  1083. should also be obvious.
  1084.  
  1085. If you are looking to expand a wildcard filename, then most systems have
  1086. the `glob()' function; also check out `fnmatch()' to match filenames
  1087. against a wildcard, or `ftw()' to traverse entire directory trees.
  1088.  
  1089. 2.4 How can I find out if someone else has a file open?
  1090. =======================================================
  1091.  
  1092. This is another candidate for "Frequently Unanswered Questions" because, in
  1093. general, your program should never be interested in whether someone else
  1094. has the file open. If you need to deal with concurrent access to the file,
  1095. then you should be looking at advisory locking.
  1096.  
  1097. This is, in general, too hard to do anyway. Tools like `fuser' and `lsof'
  1098. that find out about open files do so by grovelling through kernel data
  1099. structures in a most unhealthy fashion. You can't usefully invoke them from
  1100. a program, either, because by the time you've found out that the file
  1101. is/isn't open, the information may already be out of date.
  1102.  
  1103. 2.5 How do I 'lock' a file?
  1104. ===========================
  1105.  
  1106. There are three main file locking mechanisms available. All of them are
  1107. "advisory"[*], which means that they rely on programs co-operating in order
  1108. to work.  It is therefore vital that all programs in an application should
  1109. be consistent in their locking regime, and great care is required when your
  1110. programs may be sharing files with third-party software.
  1111.  
  1112. [*] Well, actually some Unices permit mandatory locking via the sgid bit -
  1113. RTFM for this hack.
  1114.  
  1115. Some applications use lock files - something like "filename.lock".  Simply
  1116. testing for the existence of such files is inadequate though, since a
  1117. process may have been killed while holding the lock. The method used by
  1118. UUCP (probably the most notable example: it uses lock files for controlling
  1119. access to modems, remote systems etc.) is to store the PID in the lockfile,
  1120. and test if that pid is still running. Even this isn't enough to be sure
  1121. (since PIDs are recycled); it has to have a backstop check to see if the
  1122. lockfile is old, which means that the process holding the lock must update
  1123. the file regularly. Messy.
  1124.  
  1125. The locking functions are:
  1126.  
  1127.          flock();
  1128.          lockf();
  1129.          fcntl();
  1130.  
  1131. `flock()' originates with BSD, and is now available in most (but not all)
  1132. Unices.  It is simple and effective on a single host, but doesn't work at
  1133. all with NFS.  It locks an entire file. Perhaps rather deceptively, the
  1134. popular Perl programming language implements its own `flock()' where
  1135. necessary, conveying the illusion of true portability.
  1136.  
  1137. `fcntl()' is the only POSIX-compliant locking mechanism, and is therefore
  1138. the only truly portable lock.  It is also the most powerful, and the
  1139. hardest to use.  For NFS-mounted file systems, `fcntl()' requests are
  1140. passed to a daemon (`rpc.lockd'), which communicates with the lockd on the
  1141. server host.  Unlike `flock()' it is capable of record-level locking.
  1142.  
  1143. `lockf()' is merely a simplified programming interface to the locking
  1144. functions of `fcntl()'.
  1145.  
  1146. Whatever locking mechanism you use, it is important to sync all your file
  1147. IO while the lock is active:
  1148.  
  1149.          lock(fd);
  1150.          write_to(some_function_of(fd));
  1151.          flush_output_to(fd); /* NEVER unlock while output may be buffered */
  1152.          unlock(fd);
  1153.          do_something_else;   /* another process might update it */
  1154.          lock(fd);
  1155.          seek(fd, somewhere); /* because our old file pointer is not safe */
  1156.          do_something_with(fd);
  1157.          ...
  1158.  
  1159. A few useful `fcntl()' locking recipes (error handling omitted for
  1160. simplicity) are:
  1161.  
  1162.      #include <fcntl.h>
  1163.      #include <unistd.h>
  1164.      
  1165.      read_lock(int fd)   /* a shared lock on an entire file */
  1166.      {
  1167.          fcntl(fd, F_SETLKW, file_lock(F_RDLCK, SEEK_SET));
  1168.      }
  1169.      
  1170.      write_lock(int fd)  /* an exclusive lock on an entire file */
  1171.      {
  1172.          fcntl(fd, F_SETLKW, file_lock(F_WRLCK, SEEK_SET));
  1173.      }
  1174.      
  1175.      append_lock(int fd) /* a lock on the _end_ of a file - other
  1176.                             processes may access existing records */
  1177.      {
  1178.          fcntl(fd, F_SETLKW, file_lock(F_WRLCK, SEEK_END));
  1179.      }
  1180.  
  1181. The function file_lock used by the above is
  1182.  
  1183.      struct flock* file_lock(short type, short whence)
  1184.      {
  1185.          static struct flock ret ;
  1186.          ret.l_type = type ;
  1187.          ret.l_start = 0 ;
  1188.          ret.l_whence = whence ;
  1189.          ret.l_len = 0 ;
  1190.          ret.l_pid = getpid() ;
  1191.          return &ret ;
  1192.      }
  1193.  
  1194. 2.6 How do I find out if a file has been updated by another process?
  1195. ====================================================================
  1196.  
  1197. This is close to being a Frequently Unanswered Question, because people
  1198. asking it are often looking for some notification from the system when a
  1199. file or directory is changed, and there is no portable way of getting this.
  1200. (IRIX has a non-standard facility for monitoring file accesses, but I've
  1201. never heard of it being available in any other flavour.)
  1202.  
  1203. In general, the best you can do is to use `fstat()' on the file. (Note: the
  1204. overhead on `fstat()' is quite low, usually much lower than the overhead of
  1205. `stat()'.) By watching the mtime and ctime of the file, you can detect when
  1206. it is modified, or deleted/linked/renamed. This is a bit kludgy, so you
  1207. might want to rethink *why* you want to do it.
  1208.  
  1209. 2.7 How does the 'du' utility work?
  1210. ===================================
  1211.  
  1212. `du' simply traverses the directory structure calling `stat()' (or more
  1213. accurately, `lstat()') on every file and directory it encounters, adding up
  1214. the number of blocks consumed by each.
  1215.  
  1216. If you want more detail about how it works, then the simple answer is:
  1217.  
  1218.      Use the source, Luke!
  1219.  
  1220. Source for BSD systems (FreeBSD, NetBSD and OpenBSD) is available as
  1221. unpacked source trees on their FTP distribution sites; source for GNU
  1222. versions of utilities is available from any of the GNU mirrors, but you
  1223. have to unpack the archives yourself.
  1224.  
  1225. 2.8 How do I find the size of a file?
  1226. =====================================
  1227.  
  1228. Use `stat()', or `fstat()' if you have the file open.
  1229.  
  1230. These calls fill in a data structure containing all the information about
  1231. the file that the system keeps track of; that includes the owner, group,
  1232. permissions, size, last access time, last modification time, etc.
  1233.  
  1234. The following routine illustrates how to use `stat()' to get the file size.
  1235.  
  1236.      #include <stdlib.h>
  1237.      #include <stdio.h>
  1238.      
  1239.      #include <sys/types.h>
  1240.      #include <sys/stat.h>
  1241.      
  1242.      int get_file_size(char *path,off_t *size)
  1243.      {
  1244.        struct stat file_stats;
  1245.      
  1246.        if(stat(path,&file_stats))
  1247.          return -1;
  1248.      
  1249.        *size = file_stats.st_size;
  1250.        return 0;
  1251.      }
  1252.  
  1253. 2.9 How do I expand '~' in a filename like the shell does?
  1254. ==========================================================
  1255.  
  1256. The standard interpretation for `~' at the start of a filename is: if alone
  1257. or followed by a `/', then substitute the current user's `HOME' directory;
  1258. if followed by the name of a user, then substitute that user's `HOME'
  1259. directory. If no valid expansion can be found, then shells will leave the
  1260. filename unchanged.
  1261.  
  1262. Be wary, however, of filenames that actually start with the `~' character.
  1263. Indiscriminate tilde-expansion can make it very difficult to specify such
  1264. filenames to a program; while quoting will prevent the shell from doing the
  1265. expansion, the quotes will have been removed by the time the program sees
  1266. the filename. As a general rule, do not try and perform tilde-expansion on
  1267. filenames that have been passed to the program on the command line or in
  1268. environment variables. (Filenames generated within the program, obtained by
  1269. prompting the user, or obtained from a configuration file, are good
  1270. candidates for tilde-expansion.)
  1271.  
  1272. Here's a piece of C++ code (using the standard string class) to do the job:
  1273.  
  1274.      string expand_path(const string& path)
  1275.      {
  1276.          if (path.length() == 0 || path[0] != '~')
  1277.            return path;
  1278.      
  1279.          const char *pfx = NULL;
  1280.          string::size_type pos = path.find_first_of('/');
  1281.      
  1282.          if (path.length() == 1 || pos == 1)
  1283.          {
  1284.              pfx = getenv("HOME");
  1285.              if (!pfx)
  1286.              {
  1287.                  // Punt. We're trying to expand ~/, but HOME isn't set
  1288.                  struct passwd *pw = getpwuid(getuid());
  1289.                  if (pw)
  1290.                    pfx = pw->pw_dir;
  1291.              }
  1292.          }
  1293.          else
  1294.          {
  1295.              string user(path,1,(pos==string::npos) ? string::npos : pos-1);
  1296.              struct passwd *pw = getpwnam(user.c_str());
  1297.              if (pw)
  1298.                pfx = pw->pw_dir;
  1299.          }
  1300.      
  1301.          // if we failed to find an expansion, return the path unchanged.
  1302.      
  1303.          if (!pfx)
  1304.            return path;
  1305.      
  1306.          string result(pfx);
  1307.      
  1308.          if (pos == string::npos)
  1309.            return result;
  1310.      
  1311.          if (result.length() == 0 || result[result.length()-1] != '/')
  1312.            result += '/';
  1313.      
  1314.          result += path.substr(pos+1);
  1315.      
  1316.          return result;
  1317.      }
  1318.  
  1319. 2.10 What can I do with named pipes (FIFOs)?
  1320. ============================================
  1321.  
  1322. 2.10.1 What is a named pipe?
  1323. ----------------------------
  1324.  
  1325. A "named pipe" is a special file that is used to transfer data between
  1326. unrelated processes. One (or more) process(es) writes to it, while another
  1327. process reads from it. Named pipes are visible in the file system and may
  1328. be viewed with ls like any other file. (Named pipes are also called fifo's,
  1329. which stands for "First In, First Out".)
  1330.  
  1331. Named pipes may be used to pass data between unrelated processes, while
  1332. normal (unnamed) pipes can only connect parent/child processes (unless you
  1333. try *very* hard).
  1334.  
  1335. Named pipes are strictly unidirectional, even on systems where anonymous
  1336. pipes are bidirectional (full-duplex).
  1337.  
  1338. 2.10.2 How do I create a named pipe?
  1339. ------------------------------------
  1340.  
  1341. To create a named pipe interactively, you'll use either `mknod' or
  1342. `mkfifo'. On some systems, mknod will be found in /etc. In other words, it
  1343. might not be on your path. See your man pages for details.
  1344.  
  1345. To make a named pipe within a C program use `mkfifo()':
  1346.  
  1347.      /* set the umask explicitly, you don't know where it's been */
  1348.      umask(0);
  1349.      if (mkfifo("test_fifo", S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP))
  1350.      {
  1351.          perror("mkfifo");
  1352.          exit(1);
  1353.      }
  1354.  
  1355. If you don't have `mkfifo()', you'll have to use `mknod()':
  1356.  
  1357.      /* set the umask explicitly, you don't know where it's been */
  1358.      umask(0);
  1359.      if (mknod("test_fifo",
  1360.                  S_IFIFO | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP,
  1361.                 0))
  1362.      {
  1363.          perror("mknod");
  1364.          exit(1);
  1365.      }
  1366.  
  1367. 2.10.3 How do I use a named pipe?
  1368. ---------------------------------
  1369.  
  1370. To use the pipe, you open it like a normal file, and use `read()' and
  1371. `write()' just as though it was a plain pipe.
  1372.  
  1373. However, the `open()' of the pipe may block. The following rules apply:
  1374.  
  1375.    * If you open for both reading and writing (O_RDWR), then the open will
  1376.      not block.
  1377.  
  1378.    * If you open for reading (O_RDONLY), the open will block until another
  1379.      process opens the FIFO for writing, unless O_NONBLOCK is specified, in
  1380.      which case the open succeeds.
  1381.  
  1382.    * If you open for writing (O_WRONLY), the open will block until another
  1383.      process opens the FIFO for reading, unless O_NONBLOCK is specified, in
  1384.      which case the open fails.
  1385.  
  1386. When reading and writing the FIFO, the same considerations apply as for
  1387. regular pipes and sockets, i.e. `read()' will return EOF when all writers
  1388. have closed, and `write()' will raise SIGPIPE when there are no readers (if
  1389. SIGPIPE is blocked or ignored, the call fails with EPIPE).
  1390.  
  1391. 2.10.4 Can I use a named pipe across NFS?
  1392. -----------------------------------------
  1393.  
  1394. No, you can't. There is no facility in the NFS protocol to do this.  (You
  1395. may be able to use a named pipe on an NFS-mounted filesystem to communicate
  1396. between processes on the same client, though.)
  1397.  
  1398. 2.10.5 Can multiple processes write to the pipe simultaneously?
  1399. ---------------------------------------------------------------
  1400.  
  1401. If each piece of data written to the pipe is less than PIPE_BUF in size,
  1402. then they will not be interleaved. However, the boundaries of writes are
  1403. not preserved; when you read from the pipe, the read call will return as
  1404. much data as possible, even if it originated from multiple writes.
  1405.  
  1406. The value of PIPE_BUF is guaranteed (by Posix) to be at least 512. It may
  1407. or may not be defined in `<limits.h>', but it can be queried for individual
  1408. pipes using `pathconf()' or `fpathconf()'.
  1409.  
  1410. 2.10.6 Using named pipes in applications
  1411. ----------------------------------------
  1412.  
  1413.      How can I implement two way communication between one server and
  1414.      several clients?
  1415.  
  1416. It is possible that more than one client is communicating with your server
  1417. at once. As long as each command they send to the server is smaller than
  1418. PIPE_BUF (see above), they can all use the same named pipe to send data to
  1419. the server. All clients can easily know the name of the server's incoming
  1420. fifo.
  1421.  
  1422. However, the server can not use a single pipe to communicate with the
  1423. clients. If more than one client is reading the same pipe, there is no way
  1424. to ensure that the appropriate client receives a given response.
  1425.  
  1426. A solution is to have the client create its own incoming pipe before
  1427. sending data to the server, or to have the server create its outgoing pipes
  1428. after receiving data from the client.
  1429.  
  1430. Using the client's process ID in the pipe's name is a common way to
  1431. identify them. Using fifo's named in this manner, each time the client
  1432. sends a command to the server, it can include its PID as part of the
  1433. command. Any returned data can be sent through the appropriately named pipe.
  1434.  
  1435. 3. Terminal I/O
  1436. ***************
  1437.  
  1438. 3.1 How can I make my program not echo input?
  1439. =============================================
  1440.  
  1441.      How can I make my program not echo input, like login does when asking
  1442.      for your password?
  1443.  
  1444. There is an easy way, and a slightly harder way:
  1445.  
  1446. The easy way, is to use `getpass()', which is probably found on almost all
  1447. Unices. It takes a string to use as a prompt. It will read up to an EOF or
  1448. newline and returns a pointer to a static area of memory holding the string
  1449. typed in.
  1450.  
  1451. The harder way is to use `tcgetattr()' and `tcsetattr()', both use a
  1452. `struct termios' to manipulate the terminal. The following two routines
  1453. should allow echoing, and non-echoing mode.
  1454.  
  1455.      #include <stdlib.h>
  1456.      #include <stdio.h>
  1457.      
  1458.      #include <termios.h>
  1459.      #include <string.h>
  1460.      
  1461.      static struct termios stored;
  1462.      
  1463.      void echo_off(void)
  1464.      {
  1465.          struct termios new;
  1466.          tcgetattr(0,&stored);
  1467.          memcpy(&new, &stored, sizeof(struct termios));
  1468.          new.c_lflag &= (~ECHO);
  1469.          tcsetattr(0,TCSANOW,&new);
  1470.          return;
  1471.      }
  1472.      
  1473.      void echo_on(void)
  1474.      {
  1475.          tcsetattr(0,TCSANOW,&stored);
  1476.          return;
  1477.      }
  1478.  
  1479. Both routines used, are defined by the POSIX standard.
  1480.  
  1481. 3.2 How can I read single characters from the terminal?
  1482. =======================================================
  1483.  
  1484.      How can I read single characters from the terminal? My program is
  1485.      always waiting for the user to press `<RETURN>'.
  1486.  
  1487. Terminals are usually in canonical mode, where input is read in lines after
  1488. it is edited. You may set this into non-canonical mode, where you set how
  1489. many characters should be read before input is given to your program. You
  1490. also may set the timer in non-canonical mode terminals to 0, this timer
  1491. flushs your buffer at set intervals. By doing this, you can use `getc()' to
  1492. grab the key pressed immediately by the user. We use `tcgetattr()' and
  1493. `tcsetattr()' both of which are defined by POSIX to manipulate the
  1494. `termios' structure.
  1495.  
  1496.      #include <stdlib.h>
  1497.      #include <stdio.h>
  1498.      
  1499.      #include <termios.h>
  1500.      #include <string.h>
  1501.      
  1502.      static struct termios stored;
  1503.      
  1504.      void set_keypress(void)
  1505.      {
  1506.          struct termios new;
  1507.      
  1508.          tcgetattr(0,&stored);
  1509.      
  1510.          memcpy(&new,&stored,sizeof(struct termios));
  1511.      
  1512.          /* Disable canonical mode, and set buffer size to 1 byte */
  1513.          new.c_lflag &= (~ICANON);
  1514.          new.c_cc[VTIME] = 0;
  1515.          new.c_cc[VMIN] = 1;
  1516.      
  1517.          tcsetattr(0,TCSANOW,&new);
  1518.          return;
  1519.      }
  1520.      
  1521.      void reset_keypress(void)
  1522.      {
  1523.          tcsetattr(0,TCSANOW,&stored);
  1524.          return;
  1525.      }
  1526.  
  1527. 3.3 How can I check and see if a key was pressed?
  1528. =================================================
  1529.  
  1530.      How can I check and see if a key was pressed? On DOS I use the
  1531.      `kbhit()' function, but there doesn't seem to be an equivalent?
  1532.  
  1533. If you set the terminal to single-character mode (see previous answer),
  1534. then (on most systems) you can use `select()' or `poll()' to test for
  1535. readability.
  1536.  
  1537. 3.4 How can I move the cursor around the screen?
  1538. ================================================
  1539.  
  1540.      How can I move the cursor around the screen? I want to do full screen
  1541.      editing without using curses.
  1542.  
  1543. Seriously, you probably *don't* want to do this. Curses knows about how to
  1544. handle all sorts of oddities that different terminal types exhibit; while
  1545. the termcap/terminfo data will tell you whether any given terminal type
  1546. possesses any of these oddities, you will probably find that correctly
  1547. handling all the combinations is a *huge* job.
  1548.  
  1549. However, if you insist on getting your hands dirty (so to speak), look into
  1550. the `termcap' functions, particularly `tputs()', `tparm()' and `tgoto()'.
  1551.  
  1552. 3.5 What are pttys?
  1553. ===================
  1554.  
  1555. Pseudo-teletypes (pttys, ptys, other variant abbreviations) are
  1556. pseudo-devices that have two parts: the "master" side, which can be thought
  1557. of as the 'user', and the "slave" side, which behaves like a standard tty
  1558. device.
  1559.  
  1560. They exist in order to provide a means to emulate the behaviour of a serial
  1561. terminal under the control of a program. For example, `telnet' uses a
  1562. pseudo-terminal on the remote system; the remote login shell sees the
  1563. behaviour it expects from a tty device, but the master side of the
  1564. pseudo-terminal is being controlled by a daemon that forwards all data over
  1565. the network. They are also used by programs such as `xterm', `expect',
  1566. `script', `screen', `emacs', and many others.
  1567.  
  1568. 3.6 How to handle a serial port or modem?
  1569. =========================================
  1570.  
  1571. todo
  1572.  
  1573. 4. System Information
  1574. *********************
  1575.  
  1576. 4.1 How can I tell how much memory my system has?
  1577. =================================================
  1578.  
  1579. This is another "Frequently Unanswered Question". In most cases, you should
  1580. not even *attempt* to find out.
  1581.  
  1582. If you really must, then it can usually be done, but in a highly
  1583. system-dependent fashion. For example, on Solaris, you can use
  1584. `sysconf(_SC_PHYS_PAGES)'; on FreeBSD, you can use `sysctl()', on Linux
  1585. there is probably something in `/proc', etc.  I'm not aware of any more
  1586. portable methods.
  1587.  
  1588. For HP-UX (9 and 10), the following code has been contributed:
  1589.  
  1590.      struct pst_static pst;
  1591.      
  1592.      if (pstat_getstatic(&pst, sizeof(pst), (size_t) 1, 0) != -1)
  1593.      {
  1594.          printf(" Page Size: %lu\n", pst.page_size);
  1595.          printf("Phys Pages: %lu\n", pst.physical_memory);
  1596.      }
  1597.  
  1598. 4.2 How do I check a user's password?
  1599. =====================================
  1600.  
  1601. 4.2.1 How do I get a user's password?
  1602. -------------------------------------
  1603.  
  1604. Traditionally user passwords were kept in the `/etc/passwd' file, on most
  1605. UNIX flavours. Which is usually of this format:
  1606.  
  1607. username:password:uid:gid:gecos field:home directory:login shell
  1608.  
  1609. Though this has changed with time, now user information may be kept on
  1610. other hosts, or not necessarily in the `/etc/passwd' file. Modern
  1611. implementations also made use of "shadow" password files which hold the
  1612. password, along with sensitive information. This file would be readable
  1613. only by privileged users.
  1614.  
  1615. The password is usually not in clear text, but encrypted due to security
  1616. concerns.
  1617.  
  1618. POSIX defines a suite of routines which can be used to access this database
  1619. for queries. The quickest way to get an individual record for a user is
  1620. with the `getpwnam()' and `getpwuid()' routines. Both return a pointer to a
  1621. struct passwd, which holds the users information in various members.
  1622. `getpwnam()' accepts a string holding the user's name, `getpwuid()' accepts
  1623. a uid (type `uid_t' as defined by POSIX). Both return NULL if they fail.
  1624.  
  1625. However, as explained earlier, a shadow database exists on most modern
  1626. systems to hold sensitive information, namely the password. Some systems
  1627. only return the password if the calling uid is of the superuser, others
  1628. require you to use another suite of functions for the shadow password
  1629. database. If this is the case you need to make use of `getspnam()', which
  1630. accepts a username and returns a struct spwd. Again, in order to
  1631. successfully do this, you will need to have privileges. (On some systems,
  1632. notably HP-UX and SCO, you may need to use `getprpwnam()' instead.)
  1633.  
  1634. 4.2.2 How do I get shadow passwords by uid?
  1635. -------------------------------------------
  1636.  
  1637.      My system uses the getsp* suite of routines to get the sensitive user
  1638.      information. However I do not have `getspuid()', only `getspnam()'.
  1639.      How do I work around this, and get by uid?
  1640.  
  1641. The work around is relatively painless. The following routine should go
  1642. straight into your personal utility library:
  1643.  
  1644.      #include <stdlib.h>
  1645.      #include <stdio.h>
  1646.      
  1647.      #include <pwd.h>
  1648.      #include <shadow.h>
  1649.      
  1650.      struct spwd *getspuid(uid_t pw_uid)
  1651.      {
  1652.        struct spwd *shadow;
  1653.        struct passwd *ppasswd;
  1654.      
  1655.        if( ((ppasswd = getpwuid(pw_uid)) == NULL)
  1656.            || ((shadow = getspnam(ppasswd->pw_name)) == NULL))
  1657.          return NULL;
  1658.      
  1659.        return shadow;
  1660.      }
  1661.  
  1662. The problem is, that some systems do not keep the uid, or other information
  1663. in the shadow database.
  1664.  
  1665. 4.2.3 How do I verify a user's password?
  1666. ----------------------------------------
  1667.  
  1668. The fundamental problem here is, that various authentication systems exist,
  1669. and passwords aren't always what they seem. Also with the traditional one
  1670. way encryption method used by most UNIX flavours (out of the box), the
  1671. encryption algorithm may differ, some systems use a one way DES encryption,
  1672. others like the international release of FreeBSD use MD5.
  1673.  
  1674. The most popular way is to have a one way encryption algorithm, where the
  1675. password cannot be decrypted. Instead the password is taken in clear text
  1676. from input, and encrypted and checked against the encrypted password in the
  1677. database. The details of how to encrypt should really come from your man
  1678. page for `crypt()', but here's a usual version:
  1679.  
  1680.      /* given a plaintext password and an encrypted password, check if
  1681.       * they match; returns 1 if they match, 0 otherwise.
  1682.       */
  1683.      
  1684.      int check_pass(const char *plainpw, const char *cryptpw)
  1685.      {
  1686.          return strcmp(crypt(plainpw,cryptpw), cryptpw) == 0;
  1687.      }
  1688.  
  1689. This works because the salt used in encrypting the password is stored as an
  1690. initial substring of the encrypted value.
  1691.  
  1692. *WARNING:* on some systems, password encryption is actually done with a
  1693. variant of crypt called `bigcrypt()'.
  1694.  
  1695. 5. Miscellaneous programming
  1696. ****************************
  1697.  
  1698. 5.1 How do I compare strings using wildcards?
  1699. =============================================
  1700.  
  1701. The answer to *that* depends on what exactly you mean by "wildcards".
  1702.  
  1703. There are two quite different concepts that qualify as "wildcards". They
  1704. are:
  1705.  
  1706. *Filename patterns*
  1707.      These are what the shell uses for filename expansion ("globbing")
  1708.  
  1709. *Regular Expressions*
  1710.      These are used by editors, `grep', etc. for matching text, but they
  1711.      normally *aren't* applied to filenames
  1712.  
  1713. 5.1.1 How do I compare strings using filename patterns?
  1714. -------------------------------------------------------
  1715.  
  1716. Unless you are unlucky, your system should have a function `fnmatch()' to
  1717. do filename matching. This generally allows only the Bourne shell style of
  1718. pattern; i.e. it recognises `*', `[...]' and `?', but probably won't
  1719. support the more arcane patterns available in the Korn and Bourne-Again
  1720. shells.
  1721.  
  1722. If you don't have this function, then rather than reinvent the wheel, you
  1723. are probably better off snarfing a copy from the BSD or GNU sources.
  1724.  
  1725. Also, for the common cases of matching actual filenames, look for `glob()',
  1726. which will find all existing files matching a pattern.
  1727.  
  1728. 5.1.2 How do I compare strings using regular expressions?
  1729. ---------------------------------------------------------
  1730.  
  1731. There are a number of slightly different syntaxes for regular expressions;
  1732. most systems use at least two: the one recognised by `ed', sometimes known
  1733. as "Basic Regular Expressions", and the one recognised by `egrep',
  1734. "Extended Regular Expressions". Perl has it's own slightly different
  1735. flavour, as does Emacs.
  1736.  
  1737. To support this multitude of formats, there is a corresponding multitude of
  1738. implementations. Systems will generally have regexp-matching functions
  1739. (usually `regcomp()' and `regexec()') supplied, but be wary; some systems
  1740. have more than one implementation of these functions available, with
  1741. different interfaces. In addition, there are many library implementations
  1742. available. (It's common, BTW, for regexps to be compiled to an internal
  1743. form before use, on the assumption that you may compare several separate
  1744. strings against the same regexp.)
  1745.  
  1746. One library available for this is the `rx' library, available from the GNU
  1747. mirrors. This seems to be under active development, which may be a good or
  1748. a bad thing depending on your point of view :-)
  1749.  
  1750. 5.2 What's the best way to send mail from a program?
  1751. ====================================================
  1752.  
  1753. There are several ways to send email from a Unix program. Which is the best
  1754. method to use in a given situation varies, so I'll present two of them.  A
  1755. third possibility, not covered here, is to connect to a local SMTP port (or
  1756. a smarthost) and use SMTP directly; see RFC 821.
  1757.  
  1758. 5.2.1 The simple method: /bin/mail
  1759. ----------------------------------
  1760.  
  1761. For simple applications, it may be sufficient to invoke `mail' (usually
  1762. `/bin/mail', but could be `/usr/bin/mail' on some systems).
  1763.  
  1764. *WARNING:* Some versions of UCB Mail may execute commands prefixed by `~!'
  1765. or `~|' given in the message body even in non-interactive mode. This can be
  1766. a security risk.
  1767.  
  1768. Invoked as `mail -s 'subject' recipients...' it will take a message body on
  1769. standard input, and supply a default header (including the specified
  1770. subject), and pass the message to `sendmail' for delivery.
  1771.  
  1772. This example mails a test message to `root' on the local system:
  1773.  
  1774.      #include <stdio.h>
  1775.      
  1776.      #define MAILPROG "/bin/mail"
  1777.      
  1778.      int main()
  1779.      {
  1780.          FILE *mail = popen(MAILPROG " -s 'Test Message' root", "w");
  1781.          if (!mail)
  1782.          {
  1783.              perror("popen");
  1784.              exit(1);
  1785.          }
  1786.      
  1787.          fprintf(mail, "This is a test.\n");
  1788.      
  1789.          if (pclose(mail))
  1790.          {
  1791.              fprintf(stderr, "mail failed!\n");
  1792.              exit(1);
  1793.          }
  1794.      }
  1795.  
  1796. If the text to be sent is already in a file, then one can do:
  1797.  
  1798.          system(MAILPROG " -s 'file contents' root </tmp/filename");
  1799.  
  1800. These methods can be extended to more complex cases, but there are many
  1801. pitfalls to watch out for:
  1802.  
  1803.    * If using system() or popen(), you must be very careful about quoting
  1804.      arguments to protect them from filename expansion or word splitting
  1805.  
  1806.    * Constructing command lines from user-specified data is a common source
  1807.      of buffer-overrun errors and other security holes
  1808.  
  1809.    * This method does not allow for CC: or BCC: recipients to be specified
  1810.      (some versions of /bin/mail may allow this, some do not)
  1811.  
  1812. 5.2.2 Invoking the MTA directly: /usr/lib/sendmail
  1813. --------------------------------------------------
  1814.  
  1815. The `mail' program is an example of a "Mail User Agent", a program intended
  1816. to be invoked by the user to send and receive mail, but which does not
  1817. handle the actual transport. A program for transporting mail is called an
  1818. "MTA", and the most commonly found MTA on Unix systems is called
  1819. `sendmail'. There are other MTAs in use, such as `MMDF', but these
  1820. generally include a program that emulates the usual behaviour of `sendmail'.
  1821.  
  1822. Historically, `sendmail' has usually been found in `/usr/lib', but the
  1823. current trend is to move library programs out of `/usr/lib' into
  1824. directories such as `/usr/sbin' or `/usr/libexec'. As a result, one
  1825. normally invokes `sendmail' by its full path, which is system-dependent.
  1826.  
  1827. To understand how `sendmail' behaves, it's useful to understand the concept
  1828. of an "envelope". This is very much like paper mail; the envelope defines
  1829. who the message is to be delivered to, and who it is from (for the purpose
  1830. of reporting errors). Contained in the envelope are the "headers", and the
  1831. "body", separated by a blank line.  The format of the headers is specified
  1832. primarily by RFC 822; see also the MIME RFCs.
  1833.  
  1834. There are two main ways to use `sendmail' to originate a message: either
  1835. the envelope recipients can be explicitly supplied, or `sendmail' can be
  1836. instructed to deduce them from the message headers.  Both methods have
  1837. advantages and disadvantages.
  1838.  
  1839. 5.2.2.1 Supplying the envelope explicitly
  1840. .........................................
  1841.  
  1842. The recipients of a message can simply be specified on the command line.
  1843. This has the drawback that mail addresses can contain characters that give
  1844. `system()' and `popen()' considerable grief, such as single quotes, quoted
  1845. strings etc. Passing these constructs successfully through shell
  1846. interpretation presents pitfalls. (One can do it by replacing any single
  1847. quotes by the sequence single-quote backslash single-quote single-quote,
  1848. then surrounding the entire address with single quotes. Ugly, huh?)
  1849.  
  1850. Some of this unpleasantness can be avoided by eschewing the use of
  1851. `system()' or `popen()', and resorting to `fork()' and `exec()' directly.
  1852. This is sometimes necessary in any event; for example, user-installed
  1853. handlers for SIGCHLD will usually break `pclose()' to a greater or lesser
  1854. extent.
  1855.  
  1856. Here's an example:
  1857.  
  1858.      #include <sys/types.h>
  1859.      #include <sys/wait.h>
  1860.      #include <unistd.h>
  1861.      #include <stdlib.h>
  1862.      #include <fcntl.h>
  1863.      #include <sysexits.h>
  1864.      /* #include <paths.h> if you have it */
  1865.      
  1866.      #ifndef _PATH_SENDMAIL
  1867.      #define _PATH_SENDMAIL "/usr/lib/sendmail"
  1868.      #endif
  1869.      
  1870.      /* -oi means "dont treat . as a message terminator"
  1871.       * remove ,"--" if using a pre-V8 sendmail (and hope that no-one
  1872.       * ever uses a recipient address starting with a hyphen)
  1873.       * you might wish to add -oem (report errors by mail)
  1874.       */
  1875.      
  1876.      #define SENDMAIL_OPTS "-oi","--"
  1877.      
  1878.      /* this is a macro for returning the number of elements in array */
  1879.      
  1880.      #define countof(a) ((sizeof(a))/sizeof((a)[0]))
  1881.      
  1882.      /* send the contents of the file open for reading on FD to the
  1883.       * specified recipients; the file is assumed to contain RFC822 headers
  1884.       * & body, the recipient list is terminated by a NULL pointer; returns
  1885.       * -1 if error detected, otherwise the return value from sendmail
  1886.       * (which uses <sysexits.h> to provide meaningful exit codes)
  1887.       */
  1888.      
  1889.      int send_message(int fd, const char **recipients)
  1890.      {
  1891.          static const char *argv_init[] = { _PATH_SENDMAIL, SENDMAIL_OPTS };
  1892.          const char **argvec = NULL;
  1893.          int num_recip = 0;
  1894.          pid_t pid;
  1895.          int rc;
  1896.          int status;
  1897.      
  1898.          /* count number of recipients */
  1899.      
  1900.          while (recipients[num_recip])
  1901.              ++num_recip;
  1902.      
  1903.          if (!num_recip)
  1904.              return 0;    /* sending to no recipients is successful */
  1905.      
  1906.          /* alloc space for argument vector */
  1907.      
  1908.          argvec = malloc((sizeof char*) * (num_recip+countof(argv_init)+1));
  1909.          if (!argvec)
  1910.              return -1;
  1911.      
  1912.          /* initialise argument vector */
  1913.      
  1914.          memcpy(argvec, argv_init, sizeof(argv_init));
  1915.          memcpy(argvec+countof(argv_init),
  1916.                 recipients, num_recip*sizeof(char*));
  1917.          argvec[num_recip + countof(argv_init)] = NULL;
  1918.      
  1919.          /* may need to add some signal blocking here. */
  1920.      
  1921.          /* fork */
  1922.      
  1923.          switch (pid = fork())
  1924.          {
  1925.          case 0:   /* child */
  1926.      
  1927.              /* Plumbing */
  1928.              if (fd != STDIN_FILENO)
  1929.                  dup2(fd, STDIN_FILENO);
  1930.      
  1931.              /* defined elsewhere - closes all FDs >= argument */
  1932.              closeall(3);
  1933.      
  1934.              /* go for it: */
  1935.              execv(_PATH_SENDMAIL, argvec);
  1936.              _exit(EX_OSFILE);
  1937.      
  1938.          default:  /* parent */
  1939.      
  1940.              free(argvec);
  1941.              rc = waitpid(pid, &status, 0);
  1942.              if (rc < 0)
  1943.                  return -1;
  1944.              if (WIFEXITED(status))
  1945.                  return WEXITSTATUS(status);
  1946.              return -1;
  1947.      
  1948.          case -1:  /* error */
  1949.              free(argvec);
  1950.              return -1;
  1951.          }
  1952.      }
  1953.  
  1954. 5.2.2.2 Allowing sendmail to deduce the recipients
  1955. ..................................................
  1956.  
  1957. The `-t' option to `sendmail' instructs `sendmail' to parse the headers of
  1958. the message, and use all the recipient-type headers (i.e.  `To:', `Cc:' and
  1959. `Bcc:') to construct the list of envelope recipients. This has the
  1960. advantage of simplifying the `sendmail' command line, but makes it
  1961. impossible to specify recipients other than those listed in the headers.
  1962. (This is not usually a problem.)
  1963.  
  1964. As an example, here's a program to mail a file on standard input to
  1965. specified recipients as a MIME attachment. Some error checks have been
  1966. omitted for brevity. This requires the `mimencode' program from the
  1967. `metamail' distribution.
  1968.  
  1969.      #include <stdio.h>
  1970.      #include <unistd.h>
  1971.      #include <fcntl.h>
  1972.      /* #include <paths.h> if you have it */
  1973.      
  1974.      #ifndef _PATH_SENDMAIL
  1975.      #define _PATH_SENDMAIL "/usr/lib/sendmail"
  1976.      #endif
  1977.      
  1978.      #define SENDMAIL_OPTS "-oi"
  1979.      #define countof(a) ((sizeof(a))/sizeof((a)[0]))
  1980.      
  1981.      char tfilename[L_tmpnam];
  1982.      char command[128+L_tmpnam];
  1983.      
  1984.      void cleanup(void)
  1985.      {
  1986.          unlink(tfilename);
  1987.      }
  1988.      
  1989.      int main(int argc, char **argv)
  1990.      {
  1991.          FILE *msg;
  1992.          int i;
  1993.      
  1994.          if (argc < 2)
  1995.          {
  1996.              fprintf(stderr, "usage: %s recipients...\n", argv[0]);
  1997.              exit(2);
  1998.          }
  1999.      
  2000.          if (tmpnam(tfilename) == NULL
  2001.              || (msg = fopen(tfilename,"w")) == NULL)
  2002.              exit(2);
  2003.      
  2004.          atexit(cleanup);
  2005.      
  2006.          fclose(msg);
  2007.          msg = fopen(tfilename,"a");
  2008.          if (!msg)
  2009.              exit(2);
  2010.      
  2011.          /* construct recipient list */
  2012.      
  2013.          fprintf(msg, "To: %s", argv[1]);
  2014.          for (i = 2; i < argc; i++)
  2015.              fprintf(msg, ",\n\t%s", argv[i]);
  2016.          fputc('\n',msg);
  2017.      
  2018.          /* Subject */
  2019.      
  2020.          fprintf(msg, "Subject: file sent by mail\n");
  2021.      
  2022.          /* sendmail can add it's own From:, Date:, Message-ID: etc. */
  2023.      
  2024.          /* MIME stuff */
  2025.      
  2026.          fprintf(msg, "MIME-Version: 1.0\n");
  2027.          fprintf(msg, "Content-Type: application/octet-stream\n");
  2028.          fprintf(msg, "Content-Transfer-Encoding: base64\n");
  2029.      
  2030.          /* end of headers - insert a blank line */
  2031.      
  2032.          fputc('\n',msg);
  2033.          fclose(msg);
  2034.      
  2035.          /* invoke encoding program */
  2036.      
  2037.          sprintf(command, "mimencode -b >>%s", tfilename);
  2038.          if (system(command))
  2039.              exit(1);
  2040.      
  2041.          /* invoke mailer */
  2042.      
  2043.          sprintf(command, "%s %s -t <%s",
  2044.                  _PATH_SENDMAIL, SENDMAIL_OPTS, tfilename);
  2045.          if (system(command))
  2046.              exit(1);
  2047.      
  2048.          return 0;
  2049.      }
  2050.  
  2051. 6. Use of tools
  2052. ***************
  2053.  
  2054. 6.1 How can I debug the children after a fork?
  2055. ==============================================
  2056.  
  2057. Depending on the tools available there are various ways:
  2058.  
  2059. Your debugger may have options to select whether to follow the parent or
  2060. the child process (or both) after a `fork()', which may be sufficient for
  2061. some purposes.
  2062.  
  2063. Alternatively, your debugger may have an option which allows you to attach
  2064. to a running process. This can be used to attach to the child process after
  2065. it has been started. If you don't need to examine the very start of the
  2066. child process, this is usually sufficient. Otherwise, you may wish to
  2067. insert a `sleep()' call after the `fork()' in the child process, or a loop
  2068. such as the following:
  2069.  
  2070.      {
  2071.          volatile int f = 1;
  2072.          while(f);
  2073.      }
  2074.  
  2075. which will hang the child process until you explicitly set `f' to 0 using
  2076. the debugger.
  2077.  
  2078. Remember, too, that actively using a debugger isn't the only way to find
  2079. errors in your program; utilities are available to trace system calls and
  2080. signals on many unix flavours, and verbose logging is also often useful.
  2081.  
  2082. 6.2 How to build library from other libraries?
  2083. ==============================================
  2084.  
  2085. Assuming we're talking about an archive (static) library, the easiest way
  2086. is to explode all the constituent libraries into their original objects
  2087. using `ar x' in an empty directory, and combine them all back together.  Of
  2088. course, there is the potential for collision of filenames, but if the
  2089. libraries are large, you probably don't want to be combining them in the
  2090. first place....
  2091.  
  2092. 6.3 How to create shared libraries / dlls?
  2093. ==========================================
  2094.  
  2095. The precise method for creating shared libraries varies between different
  2096. systems. There are two main parts to the process; firstly the objects to be
  2097. included in the shared library must be compiled, usually with options to
  2098. indicate that the code is to be position-independent; secondly, these
  2099. objects are linked together to form the library.
  2100.  
  2101. Here's a trivial example that should illustrate the idea:
  2102.  
  2103.      /* file shrobj.c */
  2104.      
  2105.      const char *myfunc()
  2106.      {
  2107.          return "Hello World";
  2108.      }
  2109.      
  2110.      /* end shrobj.c */
  2111.      
  2112.      /* file hello.c */
  2113.      
  2114.      #include <stdio.h>
  2115.      
  2116.      extern const char *myfunc();
  2117.      
  2118.      main()
  2119.      {
  2120.          printf("%s\n", myfunc());
  2121.          return 0;
  2122.      }
  2123.      
  2124.      /* end hello.c */
  2125.      
  2126.      $ gcc -fpic -c shrobj.c
  2127.      $ gcc -shared -o libshared.so shrobj.o
  2128.      $ gcc hello.c libshared.so
  2129.      $ ./a.out
  2130.      Hello World
  2131.  
  2132. For compilers other than gcc, change the compiler options as follows:
  2133.  
  2134. AIX 3.2 using xlc (unverified)
  2135.      Drop the `-fpic', and use `-bM:SRE -bE:libshared.exp' instead of
  2136.      `-shared'. You also need to create a file `libshared.exp' containing
  2137.      the list of symbols to export, in this case `myfunc'.  In addition,
  2138.      use `-e _nostart' when linking the library (on newer versions of AIX,
  2139.      I believe this changes to `-bnoentry').
  2140.  
  2141. SCO OpenServer 5 using the SCO Development System (unverified)
  2142.      Shared libraries are only available on OS5 if you compile to ELF
  2143.      format, which requires the `-belf' option. Use `-Kpic' instead of
  2144.      `-fpic', and `cc -belf -G' for the link step.
  2145.  
  2146. Solaris using SparcWorks compilers
  2147.      Use `-pic' instead of `-fpic', and use `ld -G' instead of `gcc
  2148.      -shared'.
  2149.  
  2150. (Submission of additional entries for the above table is encouraged.)
  2151.  
  2152. Other issues to watch out for:
  2153.  
  2154.    * AIX and (I believe) Digital Unix don't require the -fpic option,
  2155.      because all code is position independent.
  2156.  
  2157.    * AIX normally requires that you create an 'export file', which is a list
  2158.      of symbols to be exported from the shared library. Some versions of the
  2159.      linker (possibly only the SLHS linker, svld?) have an option to export
  2160.      all symbols.
  2161.  
  2162.    * If you want to refer to your shared library using the conventional '-l'
  2163.      parameter to the linker, you will have to understand how shared
  2164.      libraries are searched for at runtime on your system. The most common
  2165.      method is by using the `LD_LIBRARY_PATH' environment variable, but
  2166.      there is usually an additional option to specify this at link time.
  2167.  
  2168.    * Most implementations record the expected runtime location of the shared
  2169.      library internally. Thus, moving a library from one directory to
  2170.      another may prevent it from working. Many systems have an option to
  2171.      the linker to specify the expected runtime location (the `-R' linker
  2172.      option on Solaris, for example, or the `LD_RUN_PATH' environment
  2173.      variable).
  2174.  
  2175.    * ELF and a.out implementations may have a linker option `-Bsymbolic'
  2176.      which causes internal references within the library to be resolved.
  2177.      Otherwise, on these systems, all symbol resolution is deferred to the
  2178.      final link, and individual routines in the main program can override
  2179.      ones in the library.
  2180.  
  2181. 6.4 Can I replace objects in a shared library?
  2182. ==============================================
  2183.  
  2184. Generally, no.
  2185.  
  2186. On most systems (except AIX), when you link objects to form a shared
  2187. library, it's rather like linking an executable; the objects don't retain
  2188. their individual identity. As a result, it's generally not possible to
  2189. extract or replace individual objects from a shared library.
  2190.  
  2191. 6.5 How can I generate a stack dump from within a running program?
  2192. ==================================================================
  2193.  
  2194. Some systems provide library functions for unwinding the stack, so that you
  2195. can (for example) generate a stack dump in an error-handling function.
  2196. However, these are highly system-specific, and only a minority of systems
  2197. have them.
  2198.  
  2199. A possible workaround is to get your program to invoke a debugger *on
  2200. itself* - the details still vary slightly between systems, but the general
  2201. idea is to do this:
  2202.  
  2203.      void dump_stack(void)
  2204.      {
  2205.          char s[160];
  2206.      
  2207.          sprintf(s, "/bin/echo \"where\\ndetach\\n\" | dbx -a %d", getpid());
  2208.          system(s);
  2209.      
  2210.          return;
  2211.      }
  2212.  
  2213. You may need to tweak the commands and parameters to dbx according to your
  2214. system, or even substitute another debugger such as `gdb', but this is
  2215. still the most general solution to this particular problem that I've ever
  2216. seen. Kudos to Ralph Corderoy for this one :-)
  2217.  
  2218. Examples
  2219. ********
  2220.  
  2221. Catching SIGCHLD
  2222. ================
  2223.  
  2224.      #include <sys/types.h>  /* include this before any other sys headers */
  2225.      #include <sys/wait.h>   /* header for waitpid() and various macros */
  2226.      #include <signal.h>     /* header for signal functions */
  2227.      #include <stdio.h>      /* header for fprintf() */
  2228.      #include <unistd.h>     /* header for fork() */
  2229.      
  2230.      void sig_chld(int);     /* prototype for our SIGCHLD handler */
  2231.      
  2232.      int main()
  2233.      {
  2234.          struct sigaction act;
  2235.          pid_t pid;
  2236.      
  2237.          /* Assign sig_chld as our SIGCHLD handler */
  2238.          act.sa_handler = sig_chld;
  2239.      
  2240.          /* We don't want to block any other signals in this example */
  2241.          sigemptyset(&act.sa_mask);
  2242.      
  2243.          /*
  2244.           * We're only interested in children that have terminated, not ones
  2245.           * which have been stopped (eg user pressing control-Z at terminal)
  2246.           */
  2247.          act.sa_flags = SA_NOCLDSTOP;
  2248.      
  2249.          /*
  2250.           * Make these values effective. If we were writing a real
  2251.           * application, we would probably save the old value instead of
  2252.           * passing NULL.
  2253.           */
  2254.          if (sigaction(SIGCHLD, &act, NULL) < 0)
  2255.          {
  2256.              fprintf(stderr, "sigaction failed\n");
  2257.              return 1;
  2258.          }
  2259.      
  2260.          /* Fork */
  2261.          switch (pid = fork())
  2262.          {
  2263.          case -1:
  2264.              fprintf(stderr, "fork failed\n");
  2265.              return 1;
  2266.      
  2267.          case 0:                         /* child - finish straight away */
  2268.              _exit(7);                   /* exit status = 7 */
  2269.      
  2270.          default:                        /* parent */
  2271.              sleep(10);                  /* give child time to finish */
  2272.          }
  2273.      
  2274.          return 0;
  2275.      }
  2276.      
  2277.      /*
  2278.       * The signal handler function - only gets called when a SIGCHLD
  2279.       * is received, ie when a child terminates
  2280.       */
  2281.      void sig_chld(int signo)
  2282.      {
  2283.          int status, child_val;
  2284.      
  2285.          /* Wait for any child without blocking */
  2286.          if (waitpid(-1, &status, WNOHANG) < 0)
  2287.          {
  2288.              /*
  2289.               * calling standard I/O functions like fprintf() in a
  2290.               * signal handler is not recommended, but probably OK
  2291.               * in toy programs like this one.
  2292.               */
  2293.              fprintf(stderr, "waitpid failed\n");
  2294.              return;
  2295.          }
  2296.      
  2297.          /*
  2298.           * We now have the info in 'status' and can manipulate it using
  2299.           * the macros in wait.h.
  2300.           */
  2301.          if (WIFEXITED(status))                /* did child exit normally? */
  2302.          {
  2303.              child_val = WEXITSTATUS(status); /* get child's exit status */
  2304.              printf("child's exited normally with status %d\n", child_val);
  2305.          }
  2306.      }
  2307.  
  2308. Reading the process table - SUNOS 4 version
  2309. ===========================================
  2310.  
  2311.      #define _KMEMUSER
  2312.      #include <sys/proc.h>
  2313.      #include <kvm.h>
  2314.      #include <fcntl.h>
  2315.      
  2316.      char regexpstr[256];
  2317.      #define INIT            register char *sp=regexpstr;
  2318.      #define GETC()          (*sp++)
  2319.      #define PEEKC()         (*sp)
  2320.      #define UNGETC(c)       (--sp)
  2321.      #define RETURN(pointer) return(pointer);
  2322.      #define ERROR(val)
  2323.      #include <regexp.h>
  2324.      
  2325.      pid_t
  2326.      getpidbyname(char *name,pid_t skipit)
  2327.      {
  2328.          kvm_t *kd;
  2329.          char **arg;
  2330.          int error;
  2331.          char *p_name=NULL;
  2332.          char expbuf[256];
  2333.          char **freeme;
  2334.          int curpid;
  2335.          struct user * cur_user;
  2336.          struct user myuser;
  2337.          struct proc * cur_proc;
  2338.      
  2339.      
  2340.          if((kd=kvm_open(NULL,NULL,NULL,O_RDONLY,NULL))==NULL){
  2341.              return(-1);
  2342.          }
  2343.          sprintf(regexpstr,"^.*/%s$",name);
  2344.          compile(NULL,expbuf,expbuf+256,'\0');
  2345.      
  2346.          while(cur_proc=kvm_nextproc(kd)){
  2347.              curpid = cur_proc->p_pid;
  2348.              if((cur_user=kvm_getu(kd,cur_proc))!=NULL){
  2349.                  error=kvm_getcmd(kd,cur_proc,cur_user,&arg,NULL);
  2350.                  if(error==-1){
  2351.                      if(cur_user->u_comm[0]!='\0'){
  2352.                          p_name=cur_user->u_comm;
  2353.                      }
  2354.                  }
  2355.                  else{
  2356.                      p_name=arg[0];
  2357.                  }
  2358.              }
  2359.              if(p_name){
  2360.                  if(!strcmp(p_name,name)){
  2361.                      if(error!=-1){
  2362.                          free(arg);
  2363.                      }
  2364.                      if(skipit!=-1 && ourretval==skipit){
  2365.                          ourretval=-1;
  2366.                      }
  2367.                      else{
  2368.                          close(fd);
  2369.                          break;
  2370.                      }
  2371.                      break;
  2372.                  }
  2373.                  else{
  2374.                      if(step(p_name,expbuf)){
  2375.                          if(error!=-1){
  2376.                              free(arg);
  2377.                          }
  2378.                          break;
  2379.                      }
  2380.                  }
  2381.              }
  2382.              if(error!=-1){
  2383.                  free(arg);
  2384.              }
  2385.              p_name=NULL;
  2386.          }
  2387.          kvm_close(kd);
  2388.          if(p_name!=NULL){
  2389.              return(curpid);
  2390.          }
  2391.          return (-1);
  2392.      }
  2393.  
  2394. Reading the process table - SYSV version
  2395. ========================================
  2396.  
  2397.      pid_t
  2398.      getpidbyname(char *name,pid_t skipit)
  2399.      {
  2400.          DIR  *dp;
  2401.          struct dirent *dirp;
  2402.          prpsinfo_t retval;
  2403.          int fd;
  2404.          pid_t ourretval=-1;
  2405.      
  2406.          if((dp=opendir("/proc"))==NULL){
  2407.              return -1;
  2408.          }
  2409.          chdir("/proc");
  2410.          while((dirp=readdir(dp))!=NULL){
  2411.              if(dirp->d_name[0]!='.'){
  2412.                  if((fd=open(dirp->d_name,O_RDONLY))!=-1){
  2413.                      if(ioctl(fd,PIOCPSINFO,&retval)!=-1){
  2414.                          if(!strcmp(retval.pr_fname,name)){
  2415.                              ourretval=(pid_t)atoi(dirp->d_name);
  2416.                              if(skipit!=-1 && ourretval==skipit){
  2417.                                  ourretval=-1;
  2418.                              }
  2419.                              else{
  2420.                                  close(fd);
  2421.                                  break;
  2422.                              }
  2423.                          }
  2424.                      }
  2425.                      close(fd);
  2426.                  }
  2427.              }
  2428.          }
  2429.          closedir(dp);
  2430.          return ourretval;
  2431.      }
  2432.  
  2433. Reading the process table using popen and ps
  2434. ============================================
  2435.  
  2436.      #include <stdio.h>      /* FILE, sprintf, fgets, puts */
  2437.      #include <stdlib.h>     /* atoi, exit, EXIT_SUCCESS */
  2438.      #include <string.h>     /* strtok, strcmp */
  2439.      #include <sys/types.h>  /* pid_t */
  2440.      #include <sys/wait.h>   /* WIFEXITED, WEXITSTATUS */
  2441.      
  2442.      char *procname(pid_t pid)
  2443.      {
  2444.         static char line[133], command[80], *linep, *token, *cmd;
  2445.         FILE *fp;
  2446.         int status;
  2447.      
  2448.         if (0 == pid) return (char *)0;
  2449.      
  2450.         sprintf(command, "ps -p %d 2>/dev/null", pid);
  2451.         fp = popen(command, "r");
  2452.         if ((FILE *)0 == fp) return (char *)0;
  2453.      
  2454.         /* read the header line */
  2455.         if ((char *)0 == fgets(line, sizeof line, fp))
  2456.         {
  2457.            pclose(fp);
  2458.            return (char *)0;
  2459.         }
  2460.      
  2461.         /* figure out where the command name is from the column headings.
  2462.          * (BSD-ish machines put the COMMAND in the 5th column, while SysV
  2463.          * seems to put CMD or COMMAND in the 4th column.)
  2464.          */
  2465.         for (linep = line; ; linep = (char *)0)
  2466.         {
  2467.            if ((char *)0 == (token = strtok(linep, " \t\n")))
  2468.            {
  2469.               pclose(fp);
  2470.           return (char *)0;
  2471.            }
  2472.            if (0 == strcmp("COMMAND", token) || 0 == strcmp("CMD", token))
  2473.            { /*  we found the COMMAND column */
  2474.               cmd = token;
  2475.               break;
  2476.            }
  2477.         }
  2478.      
  2479.         /* read the ps(1) output line */
  2480.         if ((char *)0 == fgets(line, sizeof line, fp))
  2481.         {
  2482.            pclose(fp);
  2483.            return (char *)0;
  2484.         }
  2485.      
  2486.         /* grab the "word" underneath the command heading... */
  2487.         if ((char *)0 == (token = strtok(cmd, " \t\n")))
  2488.         {
  2489.            pclose(fp);
  2490.            return (char *)0;
  2491.         }
  2492.      
  2493.         status = pclose(fp);
  2494.         if (!WIFEXITED(status) || 0 != WEXITSTATUS(status))
  2495.           return (char *)0;
  2496.      
  2497.         return token;
  2498.      }
  2499.      
  2500.      int main(int argc, char *argv[])
  2501.      {
  2502.         puts(procname(atoi(argv[1])));
  2503.         exit(EXIT_SUCCESS);
  2504.      }
  2505.  
  2506. Daemon utility functions
  2507. ========================
  2508.  
  2509.      #include <unistd.h>
  2510.      #include <stdlib.h>
  2511.      #include <fcntl.h>
  2512.      #include <signal.h>
  2513.      #include <sys/types.h>
  2514.      #include <sys/wait.h>
  2515.      #include <errno.h>
  2516.      
  2517.      /* closeall() - close all FDs >= a specified value */
  2518.      
  2519.      void closeall(int fd)
  2520.      {
  2521.          int fdlimit = sysconf(_SC_OPEN_MAX);
  2522.      
  2523.          while (fd < fdlimit)
  2524.            close(fd++);
  2525.      }
  2526.      
  2527.      /* daemon() - detach process from user and disappear into the background
  2528.       * returns -1 on failure, but you can't do much except exit in that case
  2529.       * since we may already have forked. This is based on the BSD version,
  2530.       * so the caller is responsible for things like the umask, etc.
  2531.       */
  2532.      
  2533.      /* believed to work on all Posix systems */
  2534.      
  2535.      int daemon(int nochdir, int noclose)
  2536.      {
  2537.          switch (fork())
  2538.          {
  2539.              case 0:  break;
  2540.              case -1: return -1;
  2541.              default: _exit(0);          /* exit the original process */
  2542.          }
  2543.      
  2544.          if (setsid() < 0)               /* shoudn't fail */
  2545.            return -1;
  2546.      
  2547.          /* dyke out this switch if you want to acquire a control tty in */
  2548.          /* the future - not normally advisable for daemons */
  2549.      
  2550.          switch (fork())
  2551.          {
  2552.              case 0:  break;
  2553.              case -1: return -1;
  2554.              default: _exit(0);
  2555.          }
  2556.      
  2557.          if (!nochdir)
  2558.            chdir("/");
  2559.      
  2560.          if (!noclose)
  2561.          {
  2562.              closeall(0);
  2563.              open("/dev/null",O_RDWR);
  2564.              dup(0); dup(0);
  2565.          }
  2566.      
  2567.          return 0;
  2568.      }
  2569.      
  2570.      /* fork2() - like fork, but the new process is immediately orphaned
  2571.       *           (won't leave a zombie when it exits)
  2572.       * Returns 1 to the parent, not any meaningful pid.
  2573.       * The parent cannot wait() for the new process (it's unrelated).
  2574.       */
  2575.      
  2576.      /* This version assumes that you *haven't* caught or ignored SIGCHLD. */
  2577.      /* If you have, then you should just be using fork() instead anyway.  */
  2578.      
  2579.      int fork2()
  2580.      {
  2581.          pid_t pid;
  2582.          int rc;
  2583.          int status;
  2584.      
  2585.          if (!(pid = fork()))
  2586.          {
  2587.              switch (fork())
  2588.              {
  2589.                case 0:  return 0;
  2590.                case -1: _exit(errno);    /* assumes all errnos are <256 */
  2591.                default: _exit(0);
  2592.              }
  2593.          }
  2594.      
  2595.          if (pid < 0 || waitpid(pid,&status,0) < 0)
  2596.            return -1;
  2597.      
  2598.          if (WIFEXITED(status))
  2599.            if (WEXITSTATUS(status) == 0)
  2600.              return 1;
  2601.            else
  2602.              errno = WEXITSTATUS(status);
  2603.          else
  2604.            errno = EINTR;  /* well, sort of :-) */
  2605.      
  2606.          return -1;
  2607.      }
  2608.  
  2609. An example of using the above functions:
  2610.  
  2611.      #include <sys/types.h>
  2612.      #include <sys/socket.h>
  2613.      #include <netinet/in.h>
  2614.      #include <stdio.h>
  2615.      #include <stdlib.h>
  2616.      #include <syslog.h>
  2617.      #include <errno.h>
  2618.      
  2619.      int daemon(int,int);
  2620.      int fork2(void);
  2621.      void closeall(int);
  2622.      
  2623.      #define TCP_PORT 8888
  2624.      
  2625.      void errexit(const char *str)
  2626.      {
  2627.          syslog(LOG_INFO, "%s failed: %d (%m)", str, errno);
  2628.          exit(1);
  2629.      }
  2630.      
  2631.      void errreport(const char *str)
  2632.      {
  2633.          syslog(LOG_INFO, "%s failed: %d (%m)", str, errno);
  2634.      }
  2635.      
  2636.      /* the actual child process is here. */
  2637.      
  2638.      void run_child(int sock)
  2639.      {
  2640.          FILE *in = fdopen(sock,"r");
  2641.          FILE *out = fdopen(sock,"w");
  2642.          int ch;
  2643.      
  2644.          setvbuf(in, NULL, _IOFBF, 1024);
  2645.          setvbuf(out, NULL, _IOLBF, 1024);
  2646.      
  2647.          while ((ch = fgetc(in)) != EOF)
  2648.            fputc(toupper(ch), out);
  2649.      
  2650.          fclose(out);
  2651.      }
  2652.      
  2653.      /* This is the daemon's main work - listen for connections and spawn. */
  2654.      
  2655.      void process()
  2656.      {
  2657.          struct sockaddr_in addr;
  2658.          int addrlen = sizeof(addr);
  2659.          int sock = socket(AF_INET, SOCK_STREAM, 0);
  2660.          int flag = 1;
  2661.          int rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
  2662.                              &flag, sizeof(flag));
  2663.      
  2664.          if (rc < 0)
  2665.            errexit("setsockopt");
  2666.      
  2667.          addr.sin_family = AF_INET;
  2668.          addr.sin_port = htons(TCP_PORT);
  2669.          addr.sin_addr.s_addr = INADDR_ANY;
  2670.      
  2671.          rc = bind(sock, (struct sockaddr *) &addr, addrlen);
  2672.          if (rc < 0)
  2673.            errexit("bind");
  2674.      
  2675.          rc = listen(sock, 5);
  2676.          if (rc < 0)
  2677.            errexit("listen");
  2678.      
  2679.          for (;;)
  2680.          {
  2681.              rc = accept(sock, (struct sockaddr *) &addr, &addrlen);
  2682.      
  2683.              if (rc >= 0)
  2684.                switch (fork2())
  2685.                {
  2686.                  case 0:  close(sock); run_child(rc); _exit(0);
  2687.                  case -1: errreport("fork2"); close(rc); break;
  2688.                }
  2689.          }
  2690.      }
  2691.      
  2692.      int main()
  2693.      {
  2694.          if (daemon(0,0) < 0)
  2695.          {
  2696.              perror("daemon");
  2697.              exit(2);
  2698.          }
  2699.      
  2700.          openlog("test", LOG_PID, LOG_DAEMON);
  2701.      
  2702.          process();
  2703.      
  2704.          return 0;
  2705.      }
  2706.  
  2707.  
  2708. ==============================================================================
  2709. -- 
  2710. Andrew.
  2711.