home *** CD-ROM | disk | FTP | other *** search
/ Source Code 1994 March / Source_Code_CD-ROM_Walnut_Creek_March_1994.iso / compsrcs / misc / volume37 / bufer116 / part01 < prev    next >
Encoding:
Text File  |  1993-05-31  |  52.8 KB  |  1,650 lines

  1. Newsgroups: comp.sources.misc
  2. From: lmjm@doc.ic.ac.uk (Lee M J McLoughlin)
  3. Subject: v37i098:  buffer1.16 - Very Fast Tape Writer, v1.16, Part01/01
  4. Message-ID: <1993May31.030804.15289@sparky.imd.sterling.com>
  5. X-Md4-Signature: bce0a2048a5c90b7a0df354b44e6f7b0
  6. Sender: kent@sparky.imd.sterling.com (Kent Landfield)
  7. Organization: Sterling Software
  8. Date: Mon, 31 May 1993 03:08:04 GMT
  9. Approved: kent@sparky.imd.sterling.com
  10.  
  11. Submitted-by: lmjm@doc.ic.ac.uk (Lee M J McLoughlin)
  12. Posting-number: Volume 37, Issue 98
  13. Archive-name: buffer1.16/part01
  14. Environment: SUNOS, SYSV, SYSVR4, HPUX, Shared Memory, Semaphores
  15. Supersedes: buffer: Volume 37, Issue 53
  16.  
  17. This is version 1.16 of buffer.  This is a program designed to speed up 
  18. writing tapes on remote tape drives.  Requirements are shared memory and 
  19. locks which normally means that these are supported in your kernel.
  20.  
  21. Buffer has been tested under SunOS 4.0.*, SunOS 4.1.*, Solarix, HP-UX 7.0,
  22. and Gould UTX 2.1A (sv universe).
  23.  
  24. The program splits itself into two processes.  The first process reads
  25. (and reblocks) from stdin into a shared memory buffer.  The second
  26. writes from the shared memory buffer to stdout.  Doing it this way
  27. means that the writing side effectly sits in a tight write loop and
  28. doesn't have to wait for input.  Similarly for the input side.  It is
  29. this waiting that slows down other reblocking processes, like dd.
  30.  
  31. I run an archive and need to write large chunks out to tape regularly
  32. with an ethernet in the way.  Using 'buffer' in a command like:
  33.  
  34.     tar cvf - stuff | rsh somebox "buffer > /dev/rst8"
  35.  
  36. is a factor of 5 faster than the best alternative, gnu tar with its
  37. remote tape option:
  38.  
  39.     tar cvf somebox:/dev/rst8 stuff
  40.  
  41. We have been using buffer here at Imperial for a couple of years now
  42. for writing tar tapes and the main system dumps.
  43.  
  44. Thanks to Kevin Twidle <kpt@doc.ic.ac.uk> for the -p and -B code.
  45.  
  46. INSTALLATION:
  47.     Check that your kernel supports shared memory and semaphores.
  48.     A quick way to check is to build buffer and run it.
  49.     If it says "couldn't create shared memory segment" you probably
  50.     need to reconfigure and rebuild your kernel.
  51.  
  52.     To install edit the Makefile and tailor the variables to
  53.     your local systems.  Then type make.
  54.  
  55. DISCLAIMER:
  56.     This package is under the GNU GENERAL PUBLIC LICENSE!
  57.     In addtion under NO circumstances can I, or Imperial College,
  58.     be held liable for any event caused by the running or storing 
  59.     of this program or its documentation.
  60.     
  61. Lee McLoughlin.                          Phone: +44 71 589 5111 X 5085
  62. Dept of Computing, Imperial College,     Fax: +44 71 581 8024
  63. 180 Queens Gate, London, SW7 2BZ, UK.    Email: L.McLoughlin@doc.ic.ac.uk
  64. -------------------------------------------------------------------------
  65. #! /bin/sh
  66. # This is a shell archive.  Remove anything before this line, then unpack
  67. # it by saving it into a file and typing "sh file".  To overwrite existing
  68. # files, type "sh file -c".  You can also feed this as standard input via
  69. # unshar, or by typing "sh <file", e.g..  If this archive is complete, you
  70. # will see the following message at the end:
  71. #        "End of shell archive."
  72. # Contents:  README buffer.man Makefile buffer.c sem.c COPYING
  73. # Wrapped by lmjm@kea.doc.ic.ac.uk on Fri May 28 11:55:06 1993
  74. PATH=/bin:/usr/bin:/usr/ucb ; export PATH
  75. if test -f 'README' -a "${1}" != "-c" ; then 
  76.   echo shar: Will not clobber existing file \"'README'\"
  77. else
  78. echo shar: Extracting \"'README'\" \(1979 characters\)
  79. sed "s/^X//" >'README' <<'END_OF_FILE'
  80. XThis is a program designed to speed up writing tapes on remote tape
  81. Xdrives.  Requirements are shared memory and locks which normally
  82. Xmeans that these are supported in your kernel.
  83. X
  84. XBuffer has been tested under SunOS 4.0.*, SunOS 4.1.*, Solarix, HP-UX 7.0,
  85. Xand Gould UTX 2.1A (sv universe).
  86. X
  87. XThe program splits itself into two processes.  The first process reads
  88. X(and reblocks) from stdin into a shared memory buffer.  The second
  89. Xwrites from the shared memory buffer to stdout.  Doing it this way
  90. Xmeans that the writing side effectly sits in a tight write loop and
  91. Xdoesn't have to wait for input.  Similarly for the input side.  It is
  92. Xthis waiting that slows down other reblocking processes, like dd.
  93. X
  94. XI run an archive and need to write large chunks out to tape regularly
  95. Xwith an ethernet in the way.  Using 'buffer' in a command like:
  96. X
  97. X    tar cvf - stuff | rsh somebox "buffer > /dev/rst8"
  98. X
  99. Xis a factor of 5 faster than the best alternative, gnu tar with its
  100. Xremote tape option:
  101. X
  102. X    tar cvf somebox:/dev/rst8 stuff
  103. X
  104. XWe have been using buffer here at Imperial for a couple of years now
  105. Xfor writing tar tapes and the main system dumps.
  106. X
  107. XThanks to Kevin Twidle <kpt@doc.ic.ac.uk> for the -p and -B code.
  108. X
  109. XINSTALLATION:
  110. X    Check that your kernel supports shared memory and semaphores.
  111. X    A quick way to check is to build buffer and run it.
  112. X    If it says "couldn't create shared memory segment" you probably
  113. X    need to reconfigure and rebuild your kernel.
  114. X
  115. X    To install edit the Makefile and tailor the variables to
  116. X    your local systems.  Then type make.
  117. X
  118. XDISCLAIMER:
  119. X    This package is under the GNU GENERAL PUBLIC LICENSE!
  120. X    In addtion under NO circumstances can I, or Imperial College,
  121. X    be held liable for any event caused by the running or storing 
  122. X    of this program or its documentation.
  123. X    
  124. XLee McLoughlin.                          Phone: +44 71 589 5111 X 5085
  125. XDept of Computing, Imperial College,     Fax: +44 71 581 8024
  126. X180 Queens Gate, London, SW7 2BZ, UK.    Email: L.McLoughlin@doc.ic.ac.uk
  127. END_OF_FILE
  128. if test 1979 -ne `wc -c <'README'`; then
  129.     echo shar: \"'README'\" unpacked with wrong size!
  130. fi
  131. # end of 'README'
  132. fi
  133. if test -f 'buffer.man' -a "${1}" != "-c" ; then 
  134.   echo shar: Will not clobber existing file \"'buffer.man'\"
  135. else
  136. echo shar: Extracting \"'buffer.man'\" \(5087 characters\)
  137. sed "s/^X//" >'buffer.man' <<'END_OF_FILE'
  138. X.\"    Buffer.  Very fast reblocking filter speedy writing of tapes.
  139. X.\"    Copyright (C) 1990,1991  Lee McLoughlin
  140. X.\"
  141. X.\"    This program is free software; you can redistribute it and/or modify
  142. X.\"    it under the terms of the GNU General Public License as published by
  143. X.\"    the Free Software Foundation; either version 1, or (at your option)
  144. X.\"    any later version.
  145. X.\"
  146. X.\"    This program is distributed in the hope that it will be useful,
  147. X.\"    but WITHOUT ANY WARRANTY; without even the implied warranty of
  148. X.\"    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  149. X.\"    GNU General Public License for more details.
  150. X.\"
  151. X.\"    You should have received a copy of the GNU General Public License
  152. X.\"    along with this program; if not, write to the Free Software
  153. X.\"    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  154. X.\"
  155. X.\"    Lee McLoughlin.
  156. X.\"    Dept of Computing, Imperial College,
  157. X.\"    180 Queens Gate, London, SW7 2BZ, UK.
  158. X.\"
  159. X.\"    Email: L.McLoughlin@doc.ic.ac.uk
  160. X.TH BUFFER 1 "14 May 1990"
  161. X.SH NAME
  162. Xbuffer \- very fast reblocking program
  163. X.SH SYNTAX
  164. X.B buffer
  165. X[\fB\-S size\fP] [\fB\-b blocks\fP] [\fB\-s size\fP] [\fB\-m size\fP]
  166. X[\fB\-p percentage\fP] [\fB\-u microseconds\fP] [\fB-B\fR] [\fB-t\fR]
  167. X[\fB-Z\fR] [\fB-i filename\fR] [\fB-o filename\fR] 
  168. X.SH OPTIONS
  169. X.TP 5
  170. X.B \-i filename
  171. XUse the given file as the input file.  The default is stdin.
  172. X.TP
  173. X.B \-o filename
  174. XUse the given file as the output file.  The default is stdout.
  175. X.TP
  176. X.B \-S size
  177. XAfter every chunk this size has been writen print out how much been writen so far.
  178. XBy default this is not set.
  179. X.TP
  180. X.B \-s size
  181. XSize in bytes of each block.  The default blocksize is 10k to match
  182. Xthe normal output of the
  183. X.I tar(1)
  184. Xprogram.
  185. X.TP
  186. X.B \-z size
  187. XCombines the
  188. X.B \-S
  189. Xand
  190. X.B \-s
  191. Xflags.
  192. X.TP
  193. X.B \-b blocks
  194. XNumber of blocks to allocate to shared memory circular buffer.
  195. XDefaults to the number required to fill up the shared memory requested.
  196. X.TP
  197. X.B \-m size
  198. XMaximum size of the shared memory chunk to allocate for the circular
  199. Xqueue. Defaults to one megabyte.
  200. X.TP
  201. X.B \-p percentage
  202. XOnly start a write when the given percentage of the internal queue is
  203. Xfull.  A percentage around 75 often proves best. Defaults to zero.
  204. X.TP
  205. X.B \-u microseconds
  206. XAfter every write pause for this many microseconds.  Defaults to zero.
  207. X(Suprisingly a small sleep, 100 usecs, after each write can greatly enhance
  208. Xthroughput on some drives.)
  209. X.TP
  210. X.B \-B
  211. XForce each block writen to be padded out to the blocksize.  This is needed by some tape
  212. Xand cartridge drives.  Defaults to unpadded.  This only affects the
  213. Xlast block writen.
  214. X.TP
  215. X.B \-t
  216. XOn exiting print to stderr a brief message showing the total number of
  217. Xbytes written.
  218. X.TP
  219. X.B \-Z
  220. XIf reading/writing directly to a character device (like a tape drive)
  221. Xthen after each gigabyte perform an lseek to the start of the file.
  222. XUse this flag with extreme care.  If can only be used on devices where
  223. Xan lseek does not rewind the tape but does reset the kernels position
  224. Xflags.  It is used to allow more than 2 gigabytes to be written.
  225. X.PP
  226. XSizes are a number with an optional trailing character.   A 'b' 
  227. Xmultiplies the size by 512, a 'k' by 1024 and an 'm' by a meg.
  228. X.SH DESCRIPTION
  229. X.I Buffer
  230. Xreads from standard input reblocking to the given blocksize and writes
  231. Xeach block to standard output.
  232. X.PP
  233. XInternally
  234. X.I buffer
  235. Xis a pair of processes communicating via a large circular queue held
  236. Xin shared memory.  The reader process only has to block when the queue
  237. Xis full and the writer process when the queue is empty.
  238. X.I Buffer
  239. Xis designed to try and keep the writer side continuously busy so that
  240. Xit can stream when writing to tape drives.  When used to write tapes
  241. Xwith an intervening network
  242. X.I buffer
  243. Xcan result in a considerable increase in throughput.
  244. X.PP
  245. XThe default settings for
  246. X.I buffer
  247. Xare normally good enough.  If you are a heavy tape user then it is
  248. Xworth your while trying out various different combinations of options.
  249. XIn particular running a
  250. X.I buffer
  251. Xat both ends of the pipe can provide a substantial increase (see last
  252. Xexample below).
  253. X.SH EXAMPLES
  254. X.br
  255. X$ \fBbuffer < /etc/termcap > /dev/rst8\fP
  256. X.br
  257. X.sp
  258. X$ \fBtar cf - . | rsh somehost 'buffer > /dev/rst8'\fP
  259. X.br
  260. X.sp
  261. X$ \fBdump fu - | rsh somehost 'buffer -s 16k > /dev/nrst8'\fP
  262. X.br
  263. X$ \fBtar cf - . | buffer | 
  264. X.br
  265. X\ \ \ rsh somehost 'buffer -S 500K -p 75 > /dev/rst0'\fP
  266. X.SH BUGS
  267. XInternally, for printing purposes, buffer counts in terms of the
  268. Xnumber of kilobytes output.  If the blocksize you use is not a whole
  269. Xnumber of kilobytes then the numbers printed will be inaccurate.
  270. X
  271. X.SH THANKS
  272. XThanks to Kevin Twidle <kpt@doc.ic.ac.uk> for a lot of early
  273. Xsuggestions and patches to make it work with non-tar/dump tapes to
  274. Xexabyte drives.
  275. X
  276. XThanks to Andi Karrer <karrer@bernina.ethz.ch>, Rumi Zahir
  277. X<rumi@iis.ethz.ch> and Christoph Wicki <wicki@iis.ethz.ch> for patches
  278. Xto make buffer work when trying to write single tape files of greater
  279. Xthan 2 gigabytes.
  280. X
  281. X.SH COPYRIGHT
  282. X.if n Copyright (C) 1990, 1991 by Lee McLoughlin.
  283. X.if t Copyright \(co 1990, 1991 by Lee McLoughlin.
  284. X.SH SEE ALSO
  285. Xdd(1), tar(1), rsh(1)
  286. END_OF_FILE
  287. if test 5087 -ne `wc -c <'buffer.man'`; then
  288.     echo shar: \"'buffer.man'\" unpacked with wrong size!
  289. fi
  290. # end of 'buffer.man'
  291. fi
  292. if test -f 'Makefile' -a "${1}" != "-c" ; then 
  293.   echo shar: Will not clobber existing file \"'Makefile'\"
  294. else
  295. echo shar: Extracting \"'Makefile'\" \(875 characters\)
  296. sed "s/^X//" >'Makefile' <<'END_OF_FILE'
  297. X# Make the buffer program
  298. X
  299. X# Add -DSYS5 for A System 5 (USG) version of unix
  300. X#   You should also add -DSYS5 for Ultrix, AIX, and Solarix.
  301. X# Add -DDEF_SHMEM=n if you can only have n bytes of shared memory
  302. X#   (eg: -DDEF_SHMEM=524288 if you can only have half a meg.)
  303. XCFLAGS=
  304. X
  305. X# Where to install buffer and its manual pages
  306. XINSTBIN=/usr/local/bin
  307. XINSTMAN=/usr/man/manl
  308. X# The manual page section (normally l or 1)
  309. XS=l
  310. X
  311. XRM=/bin/rm
  312. XALL=README buffer.man Makefile buffer.c sem.c COPYING
  313. X
  314. Xall: buffer
  315. X
  316. Xbuffer: buffer.o sem.o
  317. X    $(CC) -o buffer $(CFLAGS) buffer.o sem.o
  318. X
  319. Xclean:
  320. X    $(RM) -f *.o core buffer .merrs
  321. X
  322. Xinstall: buffer
  323. X    cp buffer $(INSTBIN)
  324. X    chmod 111 $(INSTBIN)/buffer
  325. X    cp buffer.man $(INSTMAN)/buffer.$S
  326. X    chmod 444 $(INSTMAN)/buffer.$S
  327. X
  328. Xbuffer.tar: $(ALL)
  329. X    $(RM) -f buffer.tar
  330. X    tar cvf buffer.tar $(ALL)
  331. X
  332. Xbuffer.shar: $(ALL)
  333. X    $(RM) -f buffer.shar
  334. X    shar $(ALL) > buffer.shar
  335. END_OF_FILE
  336. if test 875 -ne `wc -c <'Makefile'`; then
  337.     echo shar: \"'Makefile'\" unpacked with wrong size!
  338. fi
  339. # end of 'Makefile'
  340. fi
  341. if test -f 'buffer.c' -a "${1}" != "-c" ; then 
  342.   echo shar: Will not clobber existing file \"'buffer.c'\"
  343. else
  344. echo shar: Extracting \"'buffer.c'\" \(18515 characters\)
  345. sed "s/^X//" >'buffer.c' <<'END_OF_FILE'
  346. X/*
  347. X    Buffer.  Very fast reblocking filter speedy writing of tapes.
  348. X    Copyright (C) 1990,1991  Lee McLoughlin
  349. X
  350. X    This program is free software; you can redistribute it and/or modify
  351. X    it under the terms of the GNU General Public License as published by
  352. X    the Free Software Foundation; either version 1, or (at your option)
  353. X    any later version.
  354. X
  355. X    This program is distributed in the hope that it will be useful,
  356. X    but WITHOUT ANY WARRANTY; without even the implied warranty of
  357. X    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  358. X    GNU General Public License for more details.
  359. X
  360. X    You should have received a copy of the GNU General Public License
  361. X    along with this program; if not, write to the Free Software
  362. X    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  363. X
  364. X    Lee McLoughlin.
  365. X    Dept of Computing, Imperial College,
  366. X    180 Queens Gate, London, SW7 2BZ, UK.
  367. X
  368. X    Email: L.McLoughlin@doc.ic.ac.uk
  369. X*/
  370. X
  371. X/* This is a reblocking process, designed to try and read from stdin
  372. X * and write to stdout - but to always try and keep the writing side
  373. X * busy.  It is meant to try and stream tape writes.
  374. X *
  375. X * This program runs in two parts.  The reader and the writer.  They
  376. X * communicate using shared memory with semaphores locking the access.
  377. X * The shared memory implements a circular list of blocks of data.
  378. X *
  379. X * L.McLoughlin, Imperial College, 1990
  380. X *
  381. X * $Log: buffer.c,v $
  382. X * Revision 1.16  1993/05/28  10:47:32  lmjm
  383. X * Debug shutdown sequence.
  384. X *
  385. X * Revision 1.15  1992/11/23  23:32:58  lmjm
  386. X * Oops!  This should be outside the ifdef
  387. X *
  388. X * Revision 1.14  1992/11/23  23:29:58  lmjm
  389. X * allow MAX_BLOCKSIZE and DEF_SHMEM to be configured
  390. X *
  391. X * Revision 1.13  1992/11/23  23:22:29  lmjm
  392. X * Printf's use %lu where appropriate.
  393. X *
  394. X * Revision 1.12  1992/11/23  23:17:55  lmjm
  395. X * Got rid of floats and use Kbyte counters instead.
  396. X *
  397. X * Revision 1.11  1992/11/03  23:11:51  lmjm
  398. X * Forgot Andi Karrer on the patch list.
  399. X *
  400. X * Revision 1.10  1992/11/03  22:58:41  lmjm
  401. X * Cleaned up the debugging prints.
  402. X *
  403. X * Revision 1.9  1992/11/03  22:53:00  lmjm
  404. X * Corrected stdin, stout and showevery use.
  405. X *
  406. X * Revision 1.8  1992/11/03  22:41:34  lmjm
  407. X * Added 2Gig patches from:
  408. X * Andi Karrer <karrer@bernina.ethz.ch>
  409. X * Rumi Zahir <rumi@iis.ethz.ch>
  410. X * Christoph Wicki <wicki@iis.ethz.ch>
  411. X *
  412. X * Revision 1.7  1992/07/23  20:42:03  lmjm
  413. X * Added 't' option to print total writen at end.
  414. X *
  415. X * Revision 1.6  1992/04/07  19:57:30  lmjm
  416. X * Added Kevins -B and -p options.
  417. X * Turn off buffering to make -S output appear ok.
  418. X * Added GPL.
  419. X *
  420. X * Revision 1.5  90/07/22  18:46:38  lmjm
  421. X * Added system 5 support.
  422. X * 
  423. X * Revision 1.4  90/07/22  18:29:48  lmjm
  424. X * Updated arg handling to be more consistent.
  425. X * Make sofar printing size an option.
  426. X * 
  427. X * Revision 1.3  90/05/15  23:27:46  lmjm
  428. X * Added -S option (show how much has been writen).
  429. X * Added -m option to specify how much shared memory to grab.
  430. X * Now tries to fill this with blocks.
  431. X * reader waits for writer to terminate and then frees the shared mem and sems.
  432. X * 
  433. X * Revision 1.2  90/01/20  21:37:59  lmjm
  434. X * Reset default number of  blocks and blocksize for best thruput of
  435. X * standard tar 10K blocks.
  436. X * Allow number of blocks to be changed.
  437. X * Don't need a hole in the circular queue since the semaphores prevent block
  438. X * clash.
  439. X * 
  440. X * Revision 1.1  90/01/17  11:30:23  lmjm
  441. X * Initial revision
  442. X * 
  443. X */
  444. X#include <unistd.h>
  445. X#include <stdio.h>
  446. X#include <signal.h>
  447. X#include <fcntl.h>
  448. X#include <sys/types.h>
  449. X#include <sys/stat.h>
  450. X#include <sys/ipc.h>
  451. X#include <sys/shm.h>
  452. X#include <sys/sem.h>
  453. X
  454. X#ifndef lint
  455. Xstatic char *rcsid = "$Header: /a/swan/home/swan/staff/csg/lmjm/src/buffer/RCS/buffer.c,v 1.16 1993/05/28 10:47:32 lmjm Exp lmjm $";
  456. X#endif
  457. X
  458. Xextern char *shmat();
  459. X
  460. X/* General macros */
  461. X#define TRUE 1
  462. X#define FALSE 0
  463. X#define K *1024
  464. X
  465. X/* Some forward declarations */
  466. Xvoid byee();
  467. Xvoid start_reader_and_writer();
  468. X
  469. X/* When showing print a note every this many bytes writen */
  470. Xint showevery = 0;
  471. X#define PRINT_EVERY 10 K
  472. X
  473. X/* Pause after every write */
  474. Xunsigned write_pause;
  475. X
  476. X/* This is the inter-process buffer - it implements a circular list
  477. X * of blocks. */
  478. X
  479. X#ifndef MAX_BLOCKSIZE
  480. X#define MAX_BLOCKSIZE (512 K)
  481. X#endif
  482. X#define DEF_BLOCKSIZE (10 K)
  483. Xint blocksize = DEF_BLOCKSIZE;
  484. X
  485. X/* Numbers of blocks in the queue. 
  486. X */
  487. X#define MAX_BLOCKS 2048
  488. Xint blocks = 1;
  489. X/* Circular increment of a buffer index */
  490. X#define INC(i) (((i)+1) == blocks ? 0 : ((i)+1))
  491. X
  492. X/* Max amount of shared memory you can allocate - can't see a way to look
  493. X * this up.
  494. X */
  495. X#ifndef DEF_SHMEM
  496. X#define DEF_SHMEM (1 K K)
  497. X#endif
  498. Xint max_shmem = DEF_SHMEM;
  499. X
  500. X/* Just a flag to show unfilled */
  501. X#define NONE (-1)
  502. X
  503. X/* the shared memory id of the buffer */
  504. Xint buffer_id = NONE;
  505. Xstruct block {
  506. X    int bytes;
  507. X    char *data;
  508. X} *curr_block;
  509. X
  510. X#define NO_BUFFER ((struct buffer *)-1)
  511. Xstruct buffer {
  512. X    /* writer will hang trying to lock this till reader fills in a block */
  513. X    int blocks_used_lock;
  514. X    /* reader will hang trying to lock this till writer empties a block */
  515. X    int blocks_free_lock;
  516. X
  517. X    int next_block_in;
  518. X    int next_block_out;
  519. X
  520. X    struct block block[ MAX_BLOCKS ];
  521. X
  522. X    /* These actual space for the blocks is here - the array extends
  523. X     * pass 1 */
  524. X    char data_space[ 1 ];
  525. X} *pbuffer = NO_BUFFER;
  526. Xint buffer_size;
  527. X
  528. Xint fdin    = 0;
  529. Xint fdout    = 1;
  530. Xint in_ISCHR    = 0;
  531. Xint out_ISCHR    = 0;
  532. Xint padblock    = FALSE;
  533. Xint writer_pid    = 0;
  534. Xint reader_pid    = 0;
  535. Xint percent    = 0;
  536. Xint debug    = 0;
  537. Xint Zflag    = 0;
  538. Xchar *progname = "buffer";
  539. X
  540. Xchar print_total = 0;
  541. X/* Number of K output */
  542. Xunsigned long outk = 0;
  543. X
  544. Xmain( argc, argv )
  545. X    int argc;
  546. X    char **argv;
  547. X{
  548. X    parse_args( argc, argv );
  549. X
  550. X    set_handlers();
  551. X
  552. X    buffer_allocate();
  553. X
  554. X    start_reader_and_writer();
  555. X
  556. X    byee( 0 );
  557. X}
  558. X
  559. Xparse_args( argc, argv )
  560. X    int argc;
  561. X    char **argv;
  562. X{
  563. X    int c;
  564. X    int iflag = 0;
  565. X    int oflag = 0;
  566. X    int zflag = 0;
  567. X    extern char *optarg;
  568. X    extern int optind;
  569. X    char blocks_given = FALSE;
  570. X    struct stat buf;
  571. X
  572. X
  573. X    while( (c = getopt( argc, argv, "BS:Zdm:s:b:p:u:ti:o:z:" )) != -1 ){
  574. X        switch( c ){
  575. X        case 't': /* Print to stderr the total no of bytes writen */
  576. X            print_total++;
  577. X            break;
  578. X        case 'u': /* pause after write for given microseconds */
  579. X            write_pause = atoi( optarg );
  580. X            break;
  581. X        case 'B':   /* Pad last block */
  582. X            padblock = TRUE;
  583. X            break;
  584. X        case 'Z':   /* Zero by lseek on the tape device */
  585. X            Zflag = TRUE;
  586. X            break;
  587. X        case 'i': /* Input file */
  588. X            iflag++;
  589. X            if( iflag > 1 ){
  590. X                fprintf( stderr, "buffer: -i given twice\n" );
  591. X                byee( -1 );
  592. X            }
  593. X            if( (fdin = open( optarg, O_RDONLY )) < 0 ){
  594. X                perror( "buffer: cannot open input file" );
  595. X                fprintf( stderr, "filename: %s\n", optarg );
  596. X                byee ( -1 );
  597. X            }
  598. X            break;
  599. X        case 'o': /* Output file */
  600. X            oflag++;
  601. X            if( oflag > 1 ){
  602. X                fprintf( stderr, "buffer: -o given twice\n" );
  603. X                byee( -1 );
  604. X            }
  605. X            if( (fdout = open( optarg, O_WRONLY | O_CREAT | O_TRUNC, 0666 )) < 0 ){
  606. X                perror( "buffer: cannot open output file" );
  607. X                fprintf( stderr, "filename: %s\n", optarg );
  608. X                byee ( -1 );
  609. X            }
  610. X            break;
  611. X        case 'S':
  612. X            /* Show every once in a while how much is printed */
  613. X            showevery = do_size( optarg );
  614. X            if( showevery <= 0 )
  615. X                showevery = PRINT_EVERY;
  616. X            break;
  617. X        case 'd':    /* debug */
  618. X            debug++;
  619. X            if( debug == 1 ){
  620. X                setbuf( stdout, NULL );
  621. X                setbuf( stderr, NULL );
  622. X                fprintf( stderr, "debugging turned on\n" );
  623. X            }
  624. X            break;
  625. X        case 'm':
  626. X            /* Max size of shared memory lump */
  627. X            max_shmem = do_size( optarg );
  628. X
  629. X            if( max_shmem < (sizeof( struct buffer ) + (blocksize * blocks)) ){
  630. X                fprintf( stderr, "max_shmem %d too low\n", max_shmem );
  631. X                byee( -1 );
  632. X            }
  633. X            break;
  634. X        case 'b':
  635. X            /* Number of blocks */
  636. X            blocks_given = TRUE;
  637. X            blocks = atoi( optarg );
  638. X            if( (blocks <= 0) || (MAX_BLOCKS < blocks) ){
  639. X                fprintf( stderr, "blocks %d out of range\n", blocks );
  640. X                byee( -1 );
  641. X            }
  642. X            break;
  643. X        case 'p':    /* percent to wait before dumping */
  644. X            percent = atoi( optarg );
  645. X
  646. X            if( (percent < 0) || (100 < percent) ){
  647. X                fprintf( stderr, "percent %d out of range\n", percent );
  648. X                byee( -1 );
  649. X            }
  650. X            if( debug )
  651. X                fprintf( stderr, "percent set to %d\n", percent );
  652. X            break;
  653. X        case 'z':
  654. X            zflag++;
  655. X            /* FALL THRU */
  656. X        case 's':    /* Size of a block */
  657. X            blocksize = do_size( optarg );
  658. X
  659. X            if( (blocksize <= 0) || (MAX_BLOCKSIZE < blocksize) ){
  660. X                fprintf( stderr, "blocksize %d out of range\n", blocksize );
  661. X                byee( -1 );
  662. X            }
  663. X            break;
  664. X        default:
  665. X            fprintf( stderr, "Usage: %s [-B] [-t] [-S size] [-m memsize] [-b blocks] [-p percent] [-s blocksize] [-u pause] [-i infile] [-o outfile] [-z size]\n",
  666. X                progname );
  667. X            fprintf( stderr, "-B = blocked device - pad out last block\n" );
  668. X            fprintf( stderr, "-t = show total amount writen at end\n" );
  669. X            fprintf( stderr, "-S size = show amount writen every size bytes\n" );
  670. X            fprintf( stderr, "-m size = size of shared mem chunk to grab\n" );
  671. X            fprintf( stderr, "-b num = number of blocks in queue\n" );
  672. X            fprintf( stderr, "-p percent = don't start writing until percent blocks filled\n" );
  673. X            fprintf( stderr, "-s size = size of a block\n" );
  674. X            fprintf( stderr, "-u usecs = microseconds to sleep after each write\n" );
  675. X            fprintf( stderr, "-i infile = file to read from\n" );
  676. X            fprintf( stderr, "-o outfile = file to write to\n" );
  677. X            fprintf( stderr, "-z size = combined -S/-s flag\n" );
  678. X            byee( -1 );
  679. X        }
  680. X    }
  681. X
  682. X    if (zflag) showevery = blocksize;
  683. X
  684. X    /* If -b was not given try and work out the max buffer size */
  685. X    if( !blocks_given ){
  686. X        blocks = (max_shmem - sizeof( struct buffer )) / blocksize;
  687. X        if( blocks <= 0 ){
  688. X            fprintf( stderr, "Cannot handle blocks that big, aborting!\n" );
  689. X            byee( -1 );
  690. X        }
  691. X        if( MAX_BLOCKS < blocks  ){
  692. X            fprintf( stderr, "Cannot handle that many blocks, aborting!\n" );
  693. X            byee( -1 );
  694. X        }
  695. X    }
  696. X
  697. X    /* check if fdin or fdout are character special files */
  698. X    if( fstat( fdin, &buf ) != 0 ){
  699. X        perror( "buffer: can't stat input file" );
  700. X        byee( -1 );
  701. X    }
  702. X    in_ISCHR = S_ISCHR( buf.st_mode );
  703. X    if( fstat( fdout, &buf ) != 0 ){
  704. X        perror( "buffer: can't stat output file" );
  705. X        byee( -1 );
  706. X    }
  707. X    out_ISCHR = S_ISCHR( buf.st_mode );
  708. X}
  709. X
  710. X/* The interrupt handler */
  711. Xshutdown()
  712. X{
  713. X    static int shutting;
  714. X    if( shutting ){
  715. X        if( debug )
  716. X            fprintf( stderr, "%s: ALREADY SHUTTING!\n", writer_pid ? "R" : "W" );
  717. X        return;
  718. X    }
  719. X    shutting = 1;
  720. X    if( debug )
  721. X        fprintf( stderr, "%s: shutdown on signal\n", writer_pid ? "R" : "W" );
  722. X
  723. X    byee( -1 );
  724. X}
  725. X
  726. Xset_handlers()
  727. X{
  728. X    if( debug )
  729. X        fprintf( stderr, "%s: setting handlers\n", writer_pid ? "R" : "W" );
  730. X
  731. X    signal( SIGHUP, shutdown );
  732. X    signal( SIGINT, shutdown );
  733. X    signal( SIGQUIT, shutdown );
  734. X    signal( SIGTERM, shutdown );
  735. X#ifdef SIGCHLD
  736. X    signal( SIGCHLD, shutdown );
  737. X#endif
  738. X#ifdef SIGCLD
  739. X    signal( SIGCLD, shutdown );
  740. X#endif
  741. X}
  742. X
  743. Xbuffer_allocate()
  744. X{
  745. X    int i;
  746. X
  747. X    /* Allow for the data space */
  748. X    buffer_size = sizeof( struct buffer ) +
  749. X        ((blocks * blocksize) - sizeof( char ));
  750. X
  751. X    /* Create the space for the buffer */
  752. X    buffer_id = shmget( IPC_PRIVATE,
  753. X               buffer_size,
  754. X               IPC_CREAT|S_IREAD|S_IWRITE );
  755. X    if( buffer_id < 0 ){
  756. X        perror( "buffer: couldn't create shared memory segment" );
  757. X        byee( -1 );
  758. X    }
  759. X
  760. X    get_buffer();
  761. X
  762. X    if( debug )
  763. X        fprintf( stderr, "pbuffer is 0x%08x, buffer_size is %d [%d x %d]\n",
  764. X            (char *)pbuffer, buffer_size, blocks, blocksize );
  765. X
  766. X#ifdef SYS5
  767. X    memset( (char *)pbuffer, '\0', buffer_size );
  768. X#else
  769. X    bzero( (char *)pbuffer, buffer_size );
  770. X#endif
  771. X    pbuffer->blocks_used_lock = -1;
  772. X    pbuffer->blocks_free_lock = -1;
  773. X
  774. X    pbuffer->blocks_used_lock = new_sem();
  775. X    /* Start it off locked - it is unlocked when a buffer gets filled in */
  776. X    lock( pbuffer->blocks_used_lock );
  777. X
  778. X    pbuffer->blocks_free_lock = new_sem();
  779. X    /* start this off so lock() can be called on it for each block
  780. X     * till all the blocks are used up */
  781. X    sem_set( pbuffer->blocks_free_lock, blocks - 1 );
  782. X
  783. X    /* Detattach the shared memory so the fork doesnt do anything odd */
  784. X    shmdt( (char *)pbuffer );
  785. X    pbuffer = NO_BUFFER;
  786. X}
  787. X
  788. Xbuffer_remove()
  789. X{
  790. X    static char removing = FALSE;
  791. X    int i;
  792. X
  793. X    /* Avoid accidental recursion */
  794. X    if( removing )
  795. X        return;
  796. X    removing = TRUE;
  797. X
  798. X    /* Buffer not yet created */
  799. X    if( buffer_id == NONE )
  800. X        return;
  801. X
  802. X    /* There should be a buffer so this must be after its detached it
  803. X     * but before the fork picks it up */
  804. X    if( pbuffer == NO_BUFFER )
  805. X        get_buffer();
  806. X
  807. X    if( debug )
  808. X        fprintf( stderr, "R: removing semaphores and buffer\n" );
  809. X    remove_sem( pbuffer->blocks_used_lock );
  810. X    remove_sem( pbuffer->blocks_free_lock );
  811. X    
  812. X    if( shmctl( buffer_id, IPC_RMID, (struct shmid_ds *)0 ) == -1 )
  813. X        perror( "buffer: failed to remove shared memory buffer" );
  814. X}
  815. X
  816. Xget_buffer()
  817. X{
  818. X    int b;
  819. X
  820. X    /* Grab the buffer space */
  821. X    pbuffer = (struct buffer *)shmat( buffer_id, (char *)0, 0 );
  822. X    if( pbuffer == NO_BUFFER ){
  823. X        perror( "buffer: failed to attach shared memory" );
  824. X        byee( -1 );
  825. X    }
  826. X
  827. X    /* Setup the data space pointers */
  828. X    for( b = 0; b < blocks; b++ )
  829. X        pbuffer->block[ b ].data =
  830. X            &pbuffer->data_space[ b * blocksize ];
  831. X
  832. X}
  833. X
  834. Xvoid
  835. Xstart_reader_and_writer()
  836. X{
  837. X    int status, deadpid;
  838. X
  839. X    fflush( stdout );
  840. X    fflush( stderr );
  841. X
  842. X    if( (writer_pid = fork()) == -1 ){
  843. X        perror( "buffer: unable to fork" );
  844. X        byee( -1 );
  845. X    }
  846. X    else if( writer_pid == 0 ){
  847. X        reader_pid = getppid();
  848. X
  849. X        /* Never trust fork() to propogate signals - reset them */
  850. X        set_handlers();
  851. X
  852. X        writer();
  853. X    }
  854. X    else {
  855. X        reader();
  856. X
  857. X        /* Now wait for the writer to finish */
  858. X        while( ((deadpid = wait( &status )) != writer_pid) &&
  859. X            deadpid != -1 )
  860. X            ;
  861. X    }
  862. X}
  863. X
  864. X/* Read from stdin into the buffer */
  865. Xreader()
  866. X{
  867. X    if( debug )
  868. X        fprintf( stderr, "R: Entering reader\n" );
  869. X
  870. X    get_buffer();
  871. X
  872. X    while( 1 ){
  873. X        get_next_free_block();
  874. X        if( ! fill_block() )
  875. X            break;
  876. X    }
  877. X
  878. X    if( debug )
  879. X        fprintf( stderr, "R: Exiting reader\n" );
  880. X}
  881. X
  882. Xget_next_free_block()
  883. X{
  884. X    /* Maybe wait till there is room in the buffer */
  885. X    lock( pbuffer->blocks_free_lock );
  886. X
  887. X    curr_block = &pbuffer->block[ pbuffer->next_block_in ];
  888. X
  889. X    pbuffer->next_block_in = INC( pbuffer->next_block_in );
  890. X}
  891. X
  892. Xfill_block()
  893. X{
  894. X    int bytes;
  895. X    char *start;
  896. X    int toread;
  897. X    static char eof_reached = 0;
  898. X    
  899. X    if( eof_reached ){
  900. X        curr_block->bytes = 0;
  901. X        unlock( pbuffer->blocks_used_lock );
  902. X        return 0;
  903. X    }
  904. X
  905. X    start = curr_block->data;
  906. X    toread = blocksize;
  907. X
  908. X    /* Fill the block with input.  This reblocks the input. */
  909. X    while( toread != 0 && (bytes = read( fdin, start, toread )) > 0 ){
  910. X        start += bytes;
  911. X        toread -= bytes;
  912. X    }
  913. X
  914. X    if( bytes == 0 ){
  915. X        eof_reached = 1;
  916. X    }
  917. X
  918. X    if( bytes < 0 ){
  919. X        perror( "buffer: failed to read input" );
  920. X        byee( -1 );
  921. X    }
  922. X
  923. X    /* number of bytes available. Zero will be taken as eof */
  924. X    if( !padblock || toread == blocksize )
  925. X        curr_block->bytes = blocksize - toread;
  926. X    else {
  927. X        if( toread ) bzero( start, toread );
  928. X        curr_block->bytes = blocksize;
  929. X    }
  930. X
  931. X    if( debug > 1 )
  932. X        fprintf( stderr, "R: got %d bytes\n", curr_block->bytes );
  933. X
  934. X    unlock( pbuffer->blocks_used_lock );
  935. X
  936. X    return curr_block->bytes;
  937. X}
  938. X
  939. X/* Write the buffer to stdout */
  940. Xwriter()
  941. X{
  942. X    int filled = 0;
  943. X    int maxfilled = (blocks * percent) / 100;
  944. X    int first_block;
  945. X
  946. X    if( debug )
  947. X        fprintf( stderr, "\tW: Entering writer\n blocks = %d\n maxfilled = %d\n",
  948. X            blocks,
  949. X            maxfilled );
  950. X
  951. X    get_buffer();
  952. X
  953. X    while( 1 ){
  954. X        if( !filled )
  955. X            first_block = pbuffer->next_block_out;
  956. X        get_next_filled_block();
  957. X        if( !data_to_write() )
  958. X            break;
  959. X
  960. X        filled++;
  961. X        if( debug > 1 )
  962. X            fprintf( stderr, "W: filled = %d\n", filled );
  963. X        if( filled >= maxfilled ){
  964. X            if( debug > 1 )
  965. X                fprintf( stderr, "W: writing\n" );
  966. X            write_blocks_to_stdout( filled, first_block );
  967. X            filled = 0;
  968. X        }
  969. X    }
  970. X
  971. X    write_blocks_to_stdout( filled, first_block );
  972. X
  973. X    if( showevery ){
  974. X        pr_out();
  975. X    }
  976. X
  977. X    if( print_total ){
  978. X        fprintf( stderr, "Kilobytes Out %lu\n", outk );
  979. X    }
  980. X
  981. X    if( debug )
  982. X        fprintf( stderr, "\tW: Exiting writer\n" );
  983. X}
  984. X
  985. Xget_next_filled_block()
  986. X{
  987. X    /* Hang till some data is available */
  988. X    lock( pbuffer->blocks_used_lock );
  989. X
  990. X    curr_block = &pbuffer->block[ pbuffer->next_block_out ];
  991. X
  992. X    pbuffer->next_block_out = INC( pbuffer->next_block_out );
  993. X}
  994. X
  995. Xdata_to_write()
  996. X{
  997. X    return curr_block->bytes;
  998. X}
  999. X
  1000. Xwrite_blocks_to_stdout( filled, first_block )
  1001. X    int filled;
  1002. X    int first_block;
  1003. X{
  1004. X    pbuffer->next_block_out = first_block;
  1005. X
  1006. X    while( filled-- ){
  1007. X        curr_block = &pbuffer->block[ pbuffer->next_block_out ];
  1008. X        pbuffer->next_block_out = INC( pbuffer->next_block_out );
  1009. X        write_block_to_stdout();
  1010. X    }
  1011. X}
  1012. X
  1013. Xwrite_block_to_stdout()
  1014. X{
  1015. X    static unsigned long out = 0;
  1016. X    static unsigned long last_gb = 0;
  1017. X    static unsigned long next_k = 0;
  1018. X    int written;
  1019. X
  1020. X    if( next_k == 0 && showevery ){
  1021. X        if( debug > 3 )
  1022. X            fprintf( stderr, "next_k = %lu showevery = %lu\n", next_k, showevery );
  1023. X        showevery = showevery / 1024;
  1024. X        next_k = showevery;
  1025. X    }
  1026. X
  1027. X    if( (written = write( fdout, curr_block->data, curr_block->bytes )) != curr_block->bytes ){
  1028. X        perror( "buffer: write of data failed" );
  1029. X        fprintf( stderr, "bytes to write=%d, bytes written=%d, total written %10luK\n", curr_block->bytes, written, outk );
  1030. X        byee( -1 );
  1031. X    }
  1032. X
  1033. X    if( write_pause ){
  1034. X        usleep( write_pause );
  1035. X    }
  1036. X
  1037. X    out = curr_block->bytes / 1024;
  1038. X    outk += out;
  1039. X    last_gb += out;
  1040. X
  1041. X    /*
  1042. X     * on character special devices (tapes), do an lseek() every 1 Gb,
  1043. X     * to overcome the 2Gb limit. This resets the file offset to
  1044. X     * zero, but -- at least on exabyte SCSI drives -- does not perform
  1045. X     * any actual action on the tape.
  1046. X     */
  1047. X    if( Zflag && last_gb >= 1 K K ){
  1048. X        last_gb = 0;
  1049. X        if( in_ISCHR )
  1050. X            (void) lseek( fdin, 0, SEEK_SET);
  1051. X        if( out_ISCHR )
  1052. X            (void) lseek( fdout, 0, SEEK_SET);
  1053. X    }
  1054. X    if( showevery ){
  1055. X        if( debug > 3 )
  1056. X            fprintf( stderr, "outk = %lu, next_k = %lu\n",
  1057. X                outk, next_k );
  1058. X        if( outk >= next_k ){
  1059. X            pr_out();
  1060. X            next_k += showevery;
  1061. X        }
  1062. X    }
  1063. X
  1064. X    unlock( pbuffer->blocks_free_lock );
  1065. X}
  1066. X
  1067. X
  1068. Xvoid
  1069. Xbyee( exit_val )
  1070. X    int exit_val;
  1071. X{
  1072. X    /* Only the parent (reader) should zap the buffer */
  1073. X    if( writer_pid != 0 )
  1074. X        buffer_remove();
  1075. X    else if( showevery )
  1076. X        fprintf( stderr, "\n" );
  1077. X    exit( exit_val );
  1078. X}
  1079. X
  1080. X/* Given a string of <num>[<suff>] returns a num
  1081. X * suff =
  1082. X *   m/M for 1meg
  1083. X *   k/K for 1k
  1084. X *   b/B for 512
  1085. X */
  1086. Xdo_size( arg )
  1087. X    char *arg;
  1088. X{
  1089. X    char format[ 20 ];
  1090. X    int ret;
  1091. X
  1092. X    *format = '\0';
  1093. X    sscanf( arg, "%d%s", &ret, format );
  1094. X
  1095. X    switch( *format ){
  1096. X    case 'm':
  1097. X    case 'M':
  1098. X        ret = ret K K;
  1099. X        break;
  1100. X    case 'k':
  1101. X    case 'K':
  1102. X        ret = ret K;
  1103. X        break;
  1104. X    case 'b':
  1105. X    case 'B':
  1106. X        ret *= 512;
  1107. X        break;
  1108. X    }
  1109. X    
  1110. X    return ret;
  1111. X}
  1112. X
  1113. Xpr_out()
  1114. X{
  1115. X    fprintf( stderr, "% 10luK\r", outk );
  1116. X}
  1117. X
  1118. X#ifdef SYS5
  1119. X#include <sys/time.h>
  1120. X
  1121. Xbzero( b, l )
  1122. X    char *b;
  1123. X    unsigned l;
  1124. X{
  1125. X    memset( b, '\0', l );
  1126. X}
  1127. X
  1128. Xusleep_back()
  1129. X{
  1130. X}
  1131. X
  1132. Xusleep( u )
  1133. X    unsigned u;
  1134. X{
  1135. X    struct itimerval old, t;
  1136. X    signal( SIGALRM, usleep_back );
  1137. X    t.it_interval.tv_sec = 0;
  1138. X    t.it_interval.tv_usec = 0;
  1139. X    t.it_value.tv_sec = u / 1000000;
  1140. X    t.it_value.tv_usec = u % 1000000;
  1141. X    setitimer( ITIMER_REAL, &t, &old );
  1142. X    pause();
  1143. X    setitimer( ITIMER_REAL, &old, NULL );
  1144. X}
  1145. X#endif
  1146. END_OF_FILE
  1147. if test 18515 -ne `wc -c <'buffer.c'`; then
  1148.     echo shar: \"'buffer.c'\" unpacked with wrong size!
  1149. fi
  1150. # end of 'buffer.c'
  1151. fi
  1152. if test -f 'sem.c' -a "${1}" != "-c" ; then 
  1153.   echo shar: Will not clobber existing file \"'sem.c'\"
  1154. else
  1155. echo shar: Extracting \"'sem.c'\" \(2766 characters\)
  1156. sed "s/^X//" >'sem.c' <<'END_OF_FILE'
  1157. X/*
  1158. X    Buffer.  Very fast reblocking filter speedy writing of tapes.
  1159. X    Copyright (C) 1990,1991  Lee McLoughlin
  1160. X
  1161. X    This program is free software; you can redistribute it and/or modify
  1162. X    it under the terms of the GNU General Public License as published by
  1163. X    the Free Software Foundation; either version 1, or (at your option)
  1164. X    any later version.
  1165. X
  1166. X    This program is distributed in the hope that it will be useful,
  1167. X    but WITHOUT ANY WARRANTY; without even the implied warranty of
  1168. X    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  1169. X    GNU General Public License for more details.
  1170. X
  1171. X    You should have received a copy of the GNU General Public License
  1172. X    along with this program; if not, write to the Free Software
  1173. X    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  1174. X
  1175. X    Lee McLoughlin.
  1176. X    Dept of Computing, Imperial College,
  1177. X    180 Queens Gate, London, SW7 2BZ, UK.
  1178. X
  1179. X    Email: L.McLoughlin@doc.ic.ac.uk
  1180. X*/
  1181. X
  1182. X/* This is a simple module to provide an easier to understand interface to
  1183. X * semaphores */
  1184. X
  1185. X#include <stdio.h>
  1186. X#include <sys/types.h>
  1187. X#include <sys/stat.h>
  1188. X#include <sys/ipc.h>
  1189. X#include <sys/sem.h>
  1190. X#include <errno.h>
  1191. X
  1192. X#if defined(SYS5) || defined(ultrix) || defined(_AIX)
  1193. Xunion semun {
  1194. X    int val;
  1195. X    struct semid_ds *buf;
  1196. X    ushort *array;
  1197. X};
  1198. X#endif
  1199. X
  1200. X/* Set a semaphore to a particular value - meant to be used before
  1201. X * first lock/unlock */
  1202. Xvoid
  1203. Xsem_set( sem_id, val )
  1204. X    int sem_id;
  1205. X    int val;
  1206. X{
  1207. X    union semun arg;
  1208. X    extern int errno;
  1209. X
  1210. X    arg.val = val;
  1211. X
  1212. X    errno = 0;
  1213. X    semctl( sem_id, 0, SETVAL, arg );
  1214. X    if( errno != 0 ){
  1215. X        perror( "buffer: internal error, sem_set" );
  1216. X        exit( -1 );
  1217. X    }
  1218. X}
  1219. X    
  1220. Xint
  1221. Xnew_sem()
  1222. X{
  1223. X    int sem;
  1224. X
  1225. X    sem = semget( IPC_PRIVATE, 1, IPC_CREAT|S_IREAD|S_IWRITE );
  1226. X    if( sem < 0 ){
  1227. X        perror( "buffer: internal error, couldn't create semaphore" );
  1228. X        exit( -1 );
  1229. X    }
  1230. X    sem_set( sem, 1 );
  1231. X
  1232. X    return sem;
  1233. X}
  1234. X
  1235. Xstatic
  1236. Xdo_sem( sem_id, pbuf, err )
  1237. X    int sem_id;
  1238. X    struct sembuf *pbuf;
  1239. X    char *err;
  1240. X{
  1241. X    /* This just keeps us going in case of EINTR */
  1242. X    while( 1 ){
  1243. X        if( semop( sem_id, pbuf, 1 ) == -1 ){
  1244. X            if( errno == EINTR ){
  1245. X                continue;
  1246. X            }
  1247. X            fprintf( stderr, "buffer: internal error pid %d, lock id %d\n", getpid(), sem_id );
  1248. X            perror( err );
  1249. X            exit( -1 );
  1250. X        }
  1251. X        return;
  1252. X    }
  1253. X}
  1254. X
  1255. Xvoid
  1256. Xlock( sem_id )
  1257. X    int sem_id;
  1258. X{
  1259. X    struct sembuf sembuf;
  1260. X
  1261. X    sembuf.sem_num = 0;
  1262. X    sembuf.sem_op = -1;
  1263. X    sembuf.sem_flg = 0;
  1264. X
  1265. X    do_sem( sem_id, &sembuf, "buffer: lock error" );
  1266. X}
  1267. X
  1268. Xvoid
  1269. Xunlock( sem_id )
  1270. X    int sem_id;
  1271. X{
  1272. X    struct sembuf sembuf;
  1273. X
  1274. X    sembuf.sem_num = 0;
  1275. X    sembuf.sem_op = 1;
  1276. X    sembuf.sem_flg = 0;
  1277. X
  1278. X    do_sem( sem_id, &sembuf, "buffer: unlock error" );
  1279. X}
  1280. X
  1281. Xvoid
  1282. Xremove_sem( sem_id )
  1283. X    int sem_id;
  1284. X{
  1285. X    if( sem_id == -1 )
  1286. X        return;
  1287. X
  1288. X    if( semctl( sem_id, 0, IPC_RMID, NULL ) == -1 )
  1289. X        perror( "buffer: internal error, failed to remove semaphore" );
  1290. X}
  1291. END_OF_FILE
  1292. if test 2766 -ne `wc -c <'sem.c'`; then
  1293.     echo shar: \"'sem.c'\" unpacked with wrong size!
  1294. fi
  1295. # end of 'sem.c'
  1296. fi
  1297. if test -f 'COPYING' -a "${1}" != "-c" ; then 
  1298.   echo shar: Will not clobber existing file \"'COPYING'\"
  1299. else
  1300. echo shar: Extracting \"'COPYING'\" \(17982 characters\)
  1301. sed "s/^X//" >'COPYING' <<'END_OF_FILE'
  1302. X            GNU GENERAL PUBLIC LICENSE
  1303. X               Version 2, June 1991
  1304. X
  1305. X Copyright (C) 1989, 1991 Free Software Foundation, Inc.
  1306. X                          675 Mass Ave, Cambridge, MA 02139, USA
  1307. X Everyone is permitted to copy and distribute verbatim copies
  1308. X of this license document, but changing it is not allowed.
  1309. X
  1310. X                Preamble
  1311. X
  1312. X  The licenses for most software are designed to take away your
  1313. Xfreedom to share and change it.  By contrast, the GNU General Public
  1314. XLicense is intended to guarantee your freedom to share and change free
  1315. Xsoftware--to make sure the software is free for all its users.  This
  1316. XGeneral Public License applies to most of the Free Software
  1317. XFoundation's software and to any other program whose authors commit to
  1318. Xusing it.  (Some other Free Software Foundation software is covered by
  1319. Xthe GNU Library General Public License instead.)  You can apply it to
  1320. Xyour programs, too.
  1321. X
  1322. X  When we speak of free software, we are referring to freedom, not
  1323. Xprice.  Our General Public Licenses are designed to make sure that you
  1324. Xhave the freedom to distribute copies of free software (and charge for
  1325. Xthis service if you wish), that you receive source code or can get it
  1326. Xif you want it, that you can change the software or use pieces of it
  1327. Xin new free programs; and that you know you can do these things.
  1328. X
  1329. X  To protect your rights, we need to make restrictions that forbid
  1330. Xanyone to deny you these rights or to ask you to surrender the rights.
  1331. XThese restrictions translate to certain responsibilities for you if you
  1332. Xdistribute copies of the software, or if you modify it.
  1333. X
  1334. X  For example, if you distribute copies of such a program, whether
  1335. Xgratis or for a fee, you must give the recipients all the rights that
  1336. Xyou have.  You must make sure that they, too, receive or can get the
  1337. Xsource code.  And you must show them these terms so they know their
  1338. Xrights.
  1339. X
  1340. X  We protect your rights with two steps: (1) copyright the software, and
  1341. X(2) offer you this license which gives you legal permission to copy,
  1342. Xdistribute and/or modify the software.
  1343. X
  1344. X  Also, for each author's protection and ours, we want to make certain
  1345. Xthat everyone understands that there is no warranty for this free
  1346. Xsoftware.  If the software is modified by someone else and passed on, we
  1347. Xwant its recipients to know that what they have is not the original, so
  1348. Xthat any problems introduced by others will not reflect on the original
  1349. Xauthors' reputations.
  1350. X
  1351. X  Finally, any free program is threatened constantly by software
  1352. Xpatents.  We wish to avoid the danger that redistributors of a free
  1353. Xprogram will individually obtain patent licenses, in effect making the
  1354. Xprogram proprietary.  To prevent this, we have made it clear that any
  1355. Xpatent must be licensed for everyone's free use or not licensed at all.
  1356. X
  1357. X  The precise terms and conditions for copying, distribution and
  1358. Xmodification follow.
  1359. X
  1360. X            GNU GENERAL PUBLIC LICENSE
  1361. X   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  1362. X
  1363. X  0. This License applies to any program or other work which contains
  1364. Xa notice placed by the copyright holder saying it may be distributed
  1365. Xunder the terms of this General Public License.  The "Program", below,
  1366. Xrefers to any such program or work, and a "work based on the Program"
  1367. Xmeans either the Program or any derivative work under copyright law:
  1368. Xthat is to say, a work containing the Program or a portion of it,
  1369. Xeither verbatim or with modifications and/or translated into another
  1370. Xlanguage.  (Hereinafter, translation is included without limitation in
  1371. Xthe term "modification".)  Each licensee is addressed as "you".
  1372. X
  1373. XActivities other than copying, distribution and modification are not
  1374. Xcovered by this License; they are outside its scope.  The act of
  1375. Xrunning the Program is not restricted, and the output from the Program
  1376. Xis covered only if its contents constitute a work based on the
  1377. XProgram (independent of having been made by running the Program).
  1378. XWhether that is true depends on what the Program does.
  1379. X
  1380. X  1. You may copy and distribute verbatim copies of the Program's
  1381. Xsource code as you receive it, in any medium, provided that you
  1382. Xconspicuously and appropriately publish on each copy an appropriate
  1383. Xcopyright notice and disclaimer of warranty; keep intact all the
  1384. Xnotices that refer to this License and to the absence of any warranty;
  1385. Xand give any other recipients of the Program a copy of this License
  1386. Xalong with the Program.
  1387. X
  1388. XYou may charge a fee for the physical act of transferring a copy, and
  1389. Xyou may at your option offer warranty protection in exchange for a fee.
  1390. X
  1391. X  2. You may modify your copy or copies of the Program or any portion
  1392. Xof it, thus forming a work based on the Program, and copy and
  1393. Xdistribute such modifications or work under the terms of Section 1
  1394. Xabove, provided that you also meet all of these conditions:
  1395. X
  1396. X    a) You must cause the modified files to carry prominent notices
  1397. X    stating that you changed the files and the date of any change.
  1398. X
  1399. X    b) You must cause any work that you distribute or publish, that in
  1400. X    whole or in part contains or is derived from the Program or any
  1401. X    part thereof, to be licensed as a whole at no charge to all third
  1402. X    parties under the terms of this License.
  1403. X
  1404. X    c) If the modified program normally reads commands interactively
  1405. X    when run, you must cause it, when started running for such
  1406. X    interactive use in the most ordinary way, to print or display an
  1407. X    announcement including an appropriate copyright notice and a
  1408. X    notice that there is no warranty (or else, saying that you provide
  1409. X    a warranty) and that users may redistribute the program under
  1410. X    these conditions, and telling the user how to view a copy of this
  1411. X    License.  (Exception: if the Program itself is interactive but
  1412. X    does not normally print such an announcement, your work based on
  1413. X    the Program is not required to print an announcement.)
  1414. X
  1415. XThese requirements apply to the modified work as a whole.  If
  1416. Xidentifiable sections of that work are not derived from the Program,
  1417. Xand can be reasonably considered independent and separate works in
  1418. Xthemselves, then this License, and its terms, do not apply to those
  1419. Xsections when you distribute them as separate works.  But when you
  1420. Xdistribute the same sections as part of a whole which is a work based
  1421. Xon the Program, the distribution of the whole must be on the terms of
  1422. Xthis License, whose permissions for other licensees extend to the
  1423. Xentire whole, and thus to each and every part regardless of who wrote it.
  1424. X
  1425. XThus, it is not the intent of this section to claim rights or contest
  1426. Xyour rights to work written entirely by you; rather, the intent is to
  1427. Xexercise the right to control the distribution of derivative or
  1428. Xcollective works based on the Program.
  1429. X
  1430. XIn addition, mere aggregation of another work not based on the Program
  1431. Xwith the Program (or with a work based on the Program) on a volume of
  1432. Xa storage or distribution medium does not bring the other work under
  1433. Xthe scope of this License.
  1434. X
  1435. X  3. You may copy and distribute the Program (or a work based on it,
  1436. Xunder Section 2) in object code or executable form under the terms of
  1437. XSections 1 and 2 above provided that you also do one of the following:
  1438. X
  1439. X    a) Accompany it with the complete corresponding machine-readable
  1440. X    source code, which must be distributed under the terms of Sections
  1441. X    1 and 2 above on a medium customarily used for software interchange; or,
  1442. X
  1443. X    b) Accompany it with a written offer, valid for at least three
  1444. X    years, to give any third party, for a charge no more than your
  1445. X    cost of physically performing source distribution, a complete
  1446. X    machine-readable copy of the corresponding source code, to be
  1447. X    distributed under the terms of Sections 1 and 2 above on a medium
  1448. X    customarily used for software interchange; or,
  1449. X
  1450. X    c) Accompany it with the information you received as to the offer
  1451. X    to distribute corresponding source code.  (This alternative is
  1452. X    allowed only for noncommercial distribution and only if you
  1453. X    received the program in object code or executable form with such
  1454. X    an offer, in accord with Subsection b above.)
  1455. X
  1456. XThe source code for a work means the preferred form of the work for
  1457. Xmaking modifications to it.  For an executable work, complete source
  1458. Xcode means all the source code for all modules it contains, plus any
  1459. Xassociated interface definition files, plus the scripts used to
  1460. Xcontrol compilation and installation of the executable.  However, as a
  1461. Xspecial exception, the source code distributed need not include
  1462. Xanything that is normally distributed (in either source or binary
  1463. Xform) with the major components (compiler, kernel, and so on) of the
  1464. Xoperating system on which the executable runs, unless that component
  1465. Xitself accompanies the executable.
  1466. X
  1467. XIf distribution of executable or object code is made by offering
  1468. Xaccess to copy from a designated place, then offering equivalent
  1469. Xaccess to copy the source code from the same place counts as
  1470. Xdistribution of the source code, even though third parties are not
  1471. Xcompelled to copy the source along with the object code.
  1472. X
  1473. X  4. You may not copy, modify, sublicense, or distribute the Program
  1474. Xexcept as expressly provided under this License.  Any attempt
  1475. Xotherwise to copy, modify, sublicense or distribute the Program is
  1476. Xvoid, and will automatically terminate your rights under this License.
  1477. XHowever, parties who have received copies, or rights, from you under
  1478. Xthis License will not have their licenses terminated so long as such
  1479. Xparties remain in full compliance.
  1480. X
  1481. X  5. You are not required to accept this License, since you have not
  1482. Xsigned it.  However, nothing else grants you permission to modify or
  1483. Xdistribute the Program or its derivative works.  These actions are
  1484. Xprohibited by law if you do not accept this License.  Therefore, by
  1485. Xmodifying or distributing the Program (or any work based on the
  1486. XProgram), you indicate your acceptance of this License to do so, and
  1487. Xall its terms and conditions for copying, distributing or modifying
  1488. Xthe Program or works based on it.
  1489. X
  1490. X  6. Each time you redistribute the Program (or any work based on the
  1491. XProgram), the recipient automatically receives a license from the
  1492. Xoriginal licensor to copy, distribute or modify the Program subject to
  1493. Xthese terms and conditions.  You may not impose any further
  1494. Xrestrictions on the recipients' exercise of the rights granted herein.
  1495. XYou are not responsible for enforcing compliance by third parties to
  1496. Xthis License.
  1497. X
  1498. X  7. If, as a consequence of a court judgment or allegation of patent
  1499. Xinfringement or for any other reason (not limited to patent issues),
  1500. Xconditions are imposed on you (whether by court order, agreement or
  1501. Xotherwise) that contradict the conditions of this License, they do not
  1502. Xexcuse you from the conditions of this License.  If you cannot
  1503. Xdistribute so as to satisfy simultaneously your obligations under this
  1504. XLicense and any other pertinent obligations, then as a consequence you
  1505. Xmay not distribute the Program at all.  For example, if a patent
  1506. Xlicense would not permit royalty-free redistribution of the Program by
  1507. Xall those who receive copies directly or indirectly through you, then
  1508. Xthe only way you could satisfy both it and this License would be to
  1509. Xrefrain entirely from distribution of the Program.
  1510. X
  1511. XIf any portion of this section is held invalid or unenforceable under
  1512. Xany particular circumstance, the balance of the section is intended to
  1513. Xapply and the section as a whole is intended to apply in other
  1514. Xcircumstances.
  1515. X
  1516. XIt is not the purpose of this section to induce you to infringe any
  1517. Xpatents or other property right claims or to contest validity of any
  1518. Xsuch claims; this section has the sole purpose of protecting the
  1519. Xintegrity of the free software distribution system, which is
  1520. Ximplemented by public license practices.  Many people have made
  1521. Xgenerous contributions to the wide range of software distributed
  1522. Xthrough that system in reliance on consistent application of that
  1523. Xsystem; it is up to the author/donor to decide if he or she is willing
  1524. Xto distribute software through any other system and a licensee cannot
  1525. Ximpose that choice.
  1526. X
  1527. XThis section is intended to make thoroughly clear what is believed to
  1528. Xbe a consequence of the rest of this License.
  1529. X
  1530. X  8. If the distribution and/or use of the Program is restricted in
  1531. Xcertain countries either by patents or by copyrighted interfaces, the
  1532. Xoriginal copyright holder who places the Program under this License
  1533. Xmay add an explicit geographical distribution limitation excluding
  1534. Xthose countries, so that distribution is permitted only in or among
  1535. Xcountries not thus excluded.  In such case, this License incorporates
  1536. Xthe limitation as if written in the body of this License.
  1537. X
  1538. X  9. The Free Software Foundation may publish revised and/or new versions
  1539. Xof the General Public License from time to time.  Such new versions will
  1540. Xbe similar in spirit to the present version, but may differ in detail to
  1541. Xaddress new problems or concerns.
  1542. X
  1543. XEach version is given a distinguishing version number.  If the Program
  1544. Xspecifies a version number of this License which applies to it and "any
  1545. Xlater version", you have the option of following the terms and conditions
  1546. Xeither of that version or of any later version published by the Free
  1547. XSoftware Foundation.  If the Program does not specify a version number of
  1548. Xthis License, you may choose any version ever published by the Free Software
  1549. XFoundation.
  1550. X
  1551. X  10. If you wish to incorporate parts of the Program into other free
  1552. Xprograms whose distribution conditions are different, write to the author
  1553. Xto ask for permission.  For software which is copyrighted by the Free
  1554. XSoftware Foundation, write to the Free Software Foundation; we sometimes
  1555. Xmake exceptions for this.  Our decision will be guided by the two goals
  1556. Xof preserving the free status of all derivatives of our free software and
  1557. Xof promoting the sharing and reuse of software generally.
  1558. X
  1559. X                NO WARRANTY
  1560. X
  1561. X  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
  1562. XFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
  1563. XOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
  1564. XPROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
  1565. XOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  1566. XMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
  1567. XTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
  1568. XPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
  1569. XREPAIR OR CORRECTION.
  1570. X
  1571. X  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
  1572. XWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
  1573. XREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
  1574. XINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
  1575. XOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
  1576. XTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
  1577. XYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
  1578. XPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
  1579. XPOSSIBILITY OF SUCH DAMAGES.
  1580. X
  1581. X             END OF TERMS AND CONDITIONS
  1582. X
  1583. X    Appendix: How to Apply These Terms to Your New Programs
  1584. X
  1585. X  If you develop a new program, and you want it to be of the greatest
  1586. Xpossible use to the public, the best way to achieve this is to make it
  1587. Xfree software which everyone can redistribute and change under these terms.
  1588. X
  1589. X  To do so, attach the following notices to the program.  It is safest
  1590. Xto attach them to the start of each source file to most effectively
  1591. Xconvey the exclusion of warranty; and each file should have at least
  1592. Xthe "copyright" line and a pointer to where the full notice is found.
  1593. X
  1594. X    <one line to give the program's name and a brief idea of what it does.>
  1595. X    Copyright (C) 19yy  <name of author>
  1596. X
  1597. X    This program is free software; you can redistribute it and/or modify
  1598. X    it under the terms of the GNU General Public License as published by
  1599. X    the Free Software Foundation; either version 2 of the License, or
  1600. X    (at your option) any later version.
  1601. X
  1602. X    This program is distributed in the hope that it will be useful,
  1603. X    but WITHOUT ANY WARRANTY; without even the implied warranty of
  1604. X    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  1605. X    GNU General Public License for more details.
  1606. X
  1607. X    You should have received a copy of the GNU General Public License
  1608. X    along with this program; if not, write to the Free Software
  1609. X    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  1610. X
  1611. XAlso add information on how to contact you by electronic and paper mail.
  1612. X
  1613. XIf the program is interactive, make it output a short notice like this
  1614. Xwhen it starts in an interactive mode:
  1615. X
  1616. X    Gnomovision version 69, Copyright (C) 19yy name of author
  1617. X    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
  1618. X    This is free software, and you are welcome to redistribute it
  1619. X    under certain conditions; type `show c' for details.
  1620. X
  1621. XThe hypothetical commands `show w' and `show c' should show the appropriate
  1622. Xparts of the General Public License.  Of course, the commands you use may
  1623. Xbe called something other than `show w' and `show c'; they could even be
  1624. Xmouse-clicks or menu items--whatever suits your program.
  1625. X
  1626. XYou should also get your employer (if you work as a programmer) or your
  1627. Xschool, if any, to sign a "copyright disclaimer" for the program, if
  1628. Xnecessary.  Here is a sample; alter the names:
  1629. X
  1630. X  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  1631. X  `Gnomovision' (which makes passes at compilers) written by James Hacker.
  1632. X
  1633. X  <signature of Ty Coon>, 1 April 1989
  1634. X  Ty Coon, President of Vice
  1635. X
  1636. XThis General Public License does not permit incorporating your program into
  1637. Xproprietary programs.  If your program is a subroutine library, you may
  1638. Xconsider it more useful to permit linking proprietary applications with the
  1639. Xlibrary.  If this is what you want to do, use the GNU Library General
  1640. XPublic License instead of this License.
  1641. END_OF_FILE
  1642. if test 17982 -ne `wc -c <'COPYING'`; then
  1643.     echo shar: \"'COPYING'\" unpacked with wrong size!
  1644. fi
  1645. # end of 'COPYING'
  1646. fi
  1647. echo shar: End of shell archive.
  1648. exit 0
  1649. exit 0 # Just in case...
  1650.