⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch07_23.htm

📁 By Tom Christiansen and Nathan Torkington ISBN 1-56592-243-3 First Edition, published August 1998
💻 HTM
字号:
<HTML><HEAD><TITLE>Recipe 7.22. Program: lockarea (Perl Cookbook)</TITLE><METANAME="DC.title"CONTENT="Perl Cookbook"><METANAME="DC.creator"CONTENT="Tom Christiansen &amp; Nathan Torkington"><METANAME="DC.publisher"CONTENT="O'Reilly &amp; Associates, Inc."><METANAME="DC.date"CONTENT="1999-07-02T01:37:48Z"><METANAME="DC.type"CONTENT="Text.Monograph"><METANAME="DC.format"CONTENT="text/html"SCHEME="MIME"><METANAME="DC.source"CONTENT="1-56592-243-3"SCHEME="ISBN"><METANAME="DC.language"CONTENT="en-US"><METANAME="generator"CONTENT="Jade 1.1/O'Reilly DocBook 3.0 to HTML 4.0"><LINKREV="made"HREF="mailto:online-books@oreilly.com"TITLE="Online Books Comments"><LINKREL="up"HREF="ch07_01.htm"TITLE="7. File Access"><LINKREL="prev"HREF="ch07_22.htm"TITLE="7.21. Program: netlock"><LINKREL="next"HREF="ch08_01.htm"TITLE="8. File Contents"></HEAD><BODYBGCOLOR="#FFFFFF"><img alt="Book Home" border="0" src="gifs/smbanner.gif" usemap="#banner-map" /><map name="banner-map"><area shape="rect" coords="1,-2,616,66" href="index.htm" alt="Perl Cookbook"><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><p><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch07_22.htm"TITLE="7.21. Program: netlock"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 7.21. Program: netlock"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><B><FONTFACE="ARIEL,HELVETICA,HELV,SANSERIF"SIZE="-1"><ACLASS="chapter"REL="up"HREF="ch07_01.htm"TITLE="7. File Access"></A></FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="chapter"HREF="ch08_01.htm"TITLE="8. File Contents"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 8. File Contents"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch07-18319">7.22. Program: lockarea</A></H2><PCLASS="para"><ACLASS="indexterm"NAME="ch07-idx-1000009810-0"></A><ACLASS="indexterm"NAME="ch07-idx-1000009810-1"></A><ACLASS="indexterm"NAME="ch07-idx-1000009810-2"></A><ACLASS="indexterm"NAME="ch07-idx-1000009810-3"></A>Perl's <CODECLASS="literal">flock</CODE> function only locks complete files, not regions of the file. Although <CODECLASS="literal">fcntl</CODE> supports locking of a file's regions, this is difficult to access from Perl, largely because no one has written an XS module that portably packs up the necessary structure.</P><PCLASS="para">The program in <ACLASS="xref"HREF="ch07_23.htm#ch07-39765"TITLE="lockarea">Example 7.11</A> implements <ICLASS="filename">fcntl</I>, but only for the three architectures it already knows about: SunOS, BSD, and Linux. If you're running something else, you'll have to figure out the layout of the <CODECLASS="literal">flock</CODE> structure. We did this by eyeballing the C-language <EMCLASS="emphasis">sys/fcntl.h</EM> <CODECLASS="literal">#include</CODE> file &nbsp;-  and running the <EMCLASS="emphasis">c2ph</EM> program to figure out alignment and typing. This program, while included with Perl, only works on systems with a strong Berkeley heritage, like those listed above. As with Unix &nbsp;-  or Perl itself &nbsp;-  you don't <EMCLASS="emphasis">have</EM> to use <EMCLASS="emphasis">c2ph</EM>, but it sure makes life easier if you can.</P><PCLASS="para">The <CODECLASS="literal">struct_flock</CODE><ACLASS="indexterm"NAME="ch07-idx-1000009816-0"></A> function in the <EMCLASS="emphasis">lockarea</EM> program packs and unpacks in the proper format for the current architectures by consulting the <CODECLASS="literal">$^O</CODE> variable, which contains your current operating system name. There is no <CODECLASS="literal">struct_flock</CODE> function declaration. It's just aliased to the architecture-specific version. Function aliasing is discussed in <ACLASS="xref"HREF="ch10_15.htm"TITLE="Redefining a Function">Recipe 10.14</A>.</P><PCLASS="para">The <EMCLASS="emphasis">lockarea</EM> program opens a temporary file, clobbering any existing contents and writing a screenful (80 by 23) of blanks. Each line is the same length.</P><PCLASS="para">The program then forks one or more times and lets all the child processes try to update the file at the same time. The first argument, <EMCLASS="emphasis">N</EM>, is the number of times to fork to produce <CODECLASS="literal">2</CODE> <CODECLASS="literal">**</CODE> <CODECLASS="literal">N</CODE> processes. So <EMCLASS="emphasis">lockarea 1</EM> makes two children, <EMCLASS="emphasis">lockarea 2</EM> makes four, <EMCLASS="emphasis">lockarea 3</EM> makes eight, <EMCLASS="emphasis">lockarea 4</EM> makes sixteen, etc. The more kids, the more contention for the locks.</P><PCLASS="para">Each process picks a random line in the file, locks just that line, and updates it. It writes its process ID into the line, prepended with a count of how many times the line has been updated:</P><PRECLASS="programlisting">4: 18584 was just here</PRE><PCLASS="para">If the line was already locked, when the lock is finally granted, the line is updated with a message indicating the process that was in the way of this process:</P><PRECLASS="programlisting">29: 24652 ZAPPED 24656</PRE><PCLASS="para">A fun demo is to run the <EMCLASS="emphasis">lockarea</EM> program in the background and the <EMCLASS="emphasis">rep</EM> program from <ACLASS="xref"HREF="ch15_01.htm"TITLE="User Interfaces">Chapter 15</A> watching the file change. Think of it as a video game for systems programmers.</P><PRECLASS="programlisting">% lockarea 5 &amp;% rep -1 'cat /tmp/lkscreen'</PRE><PCLASS="para">When you interrupt the original parent, usually with Ctrl-C or by sending it a SIGINT from the command line, it kills all its children by sending its entire <ACLASS="indexterm"NAME="ch07-idx-1000012068-0"></A><ACLASS="indexterm"NAME="ch07-idx-1000012068-1"></A>process group a signal.</P><DIVCLASS="example"><H4CLASS="example"><ACLASS="title"NAME="ch07-39765">Example 7.11: lockarea</A></H4><PRECLASS="programlisting">#!/usr/bin/perl -w# lockarea - demo record locking with fcntluse strict;my $FORKS = shift || 1;my $SLEEP = shift || 1;use Fcntl;use POSIX qw(:unistd_h :errno_h);my $COLS = 80;my $ROWS = 23;# when's the last time you saw *this* mode used correctly?open(FH, &quot;+&gt; /tmp/lkscreen&quot;)            or  die $!;select(FH);$| = 1;select STDOUT;# clear screenfor (1 .. $ROWS) {        print FH &quot; &quot; x $COLS, &quot;\n&quot;;}my $progenitor = $$;fork while $FORKS-- &gt; 0;print &quot;hello from $$\n&quot;;if ($progenitor == $$) {        $SIG{INT} = \&amp;genocide;} else {        $SIG{INT} = sub { die &quot;goodbye from $$&quot; };}while (1) {        my $line_num = int rand($ROWS);        my $line;        my $n;        # move to line        seek(FH, $n = $line_num * ($COLS+1), SEEK_SET)              or next;        # get lock        my $place = tell(FH);        my $him;        next unless defined($him = lock(*FH, $place, $COLS));        # read line        read(FH, $line, $COLS) == $COLS                             or next;        my $count = ($line =~ /(\d+)/) ? $1 : 0;        $count++;        # update line        seek(FH, $place, 0)                                         or die $!;        my $update = sprintf($him                            ? &quot;%6d: %d ZAPPED %d&quot;                            : &quot;%6d: %d was just here&quot;,                        $count, $$, $him);        my $start = int(rand($COLS - length($update)));        die &quot;XXX&quot; if $start + length($update) &gt; $COLS;        printf FH &quot;%*.*s\n&quot;, -$COLS, $COLS, &quot; &quot; x $start . $update;        # release lock and go to sleep        unlock(*FH, $place, $COLS);        sleep $SLEEP if $SLEEP;}die &quot;NOT REACHED&quot;;                              # just in case# lock($handle, $offset, $timeout) - get an fcntl locksub lock {        my ($fh, $start, $till) = @_;        ##print &quot;$$: Locking $start, $till\n&quot;;        my $lock = struct_flock(F_WRLCK, SEEK_SET, $start, $till, 0);        my $blocker = 0;        unless (fcntl($fh, F_SETLK, $lock)) {            die &quot;F_SETLK $$ @_: $!&quot; unless $! == EAGAIN || $! == EDEADLK;            fcntl($fh, F_GETLK, $lock)          or die &quot;F_GETLK $$ @_: $!&quot;;            $blocker = (struct_flock($lock))[-1];            ##print &quot;lock $$ @_: waiting for $blocker\n&quot;;            $lock = struct_flock(F_WRLCK, SEEK_SET, $start, $till, 0);            unless (fcntl($fh, F_SETLKW, $lock)) {                warn &quot;F_SETLKW $$ @_: $!\n&quot;;                return;  # undef            }        }        return $blocker;}# unlock($handle, $offset, $timeout) - release an fcntl locksub unlock {        my ($fh, $start, $till) = @_;        ##print &quot;$$: Unlocking $start, $till\n&quot;;        my $lock = struct_flock(F_UNLCK, SEEK_SET, $start, $till, 0);        fcntl($fh, F_SETLK, $lock) or die &quot;F_UNLCK $$ @_: $!&quot;;}# OS-dependent flock structures# Linux struct flock#   short l_type;#   short l_whence;#   off_t l_start;#   off_t l_len;#   pid_t l_pid;BEGIN {        # c2ph says: typedef='s2 l2 i', sizeof=16        my $FLOCK_STRUCT = 's s l l i';        sub linux_flock {            if (wantarray) {                my ($type, $whence, $start, $len, $pid) =                    unpack($FLOCK_STRUCT, $_[0]);                return ($type, $whence, $start, $len, $pid);            } else {                my ($type, $whence, $start, $len, $pid) = @_;                return pack($FLOCK_STRUCT,                        $type, $whence, $start, $len, $pid);            }        }}# SunOS struct flock:#   short   l_type;         /* F_RDLCK, F_WRLCK, or F_UNLCK */#   short   l_whence;       /* flag to choose starting offset */#   long    l_start;        /* relative offset, in bytes */#   long    l_len;          /* length, in bytes; 0 means lock to EOF */#   short   l_pid;          /* returned with F_GETLK */#   short   l_xxx;          /* reserved for future use */BEGIN {        # c2ph says: typedef='s2 l2 s2', sizeof=16        my $FLOCK_STRUCT = 's s l l s s';        sub sunos_flock {            if (wantarray) {                my ($type, $whence, $start, $len, $pid, $xxx) =                    unpack($FLOCK_STRUCT, $_[0]);                return ($type, $whence, $start, $len, $pid);            } else {                my ($type, $whence, $start, $len, $pid) = @_;                return pack($FLOCK_STRUCT,                        $type, $whence, $start, $len, $pid, 0);            }        }}# (Free)BSD struct flock:#   off_t   l_start;        /* starting offset */#   off_t   l_len;          /* len = 0 means until end of file */#   pid_t   l_pid;          /* lock owner */#   short   l_type;         /* lock type: read/write, etc. */#   short   l_whence;       /* type of l_start */BEGIN {        # c2ph says: typedef=&quot;q2 i s2&quot;, size=24        my $FLOCK_STRUCT = 'll ll i s s';   # XXX: q is ll        sub bsd_flock {            if (wantarray) {                my ($xxstart, $start, $xxlen, $len, $pid, $type, $whence) =                    unpack($FLOCK_STRUCT, $_[0]);                return ($type, $whence, $start, $len, $pid);            } else {                my ($type, $whence, $start, $len, $pid) = @_;                my ($xxstart, $xxlen) = (0,0);                return pack($FLOCK_STRUCT,                    $xxstart, $start, $xxlen, $len, $pid, $type, $whence);            }        }}# alias the fcntl structure at compile timeBEGIN {        for ($^O) {            *struct_flock =                do                           {                                    /bsd/  &amp;&amp;  \&amp;bsd_flock                                           ||                                /linux/    &amp;&amp;    \&amp;linux_flock                                           ||                              /sunos/      &amp;&amp;      \&amp;sunos_flock                                           ||                      die &quot;unknown operating system $^O, bailing out&quot;;            };        }}# install signal handler for childrenBEGIN {        my $called = 0;        sub genocide {            exit if $called++;            print &quot;$$: Time to die, kiddies.\n&quot; if $$ == $progenitor;            my $job = getpgrp();            $SIG{INT} = 'IGNORE';            kill -2, $job if $job;  # killpg(SIGINT, job)            1 while wait &gt; 0;            print &quot;$$: My turn\n&quot; if $$ == $progenitor;            exit;        }}END { &amp;genocide }<ACLASS="indexterm"NAME="ch07-idx-1000010808-0"></A><ACLASS="indexterm"NAME="ch07-idx-1000010808-1"></A><ACLASS="indexterm"NAME="ch07-idx-1000010808-2"></A><ACLASS="indexterm"NAME="ch07-idx-1000010808-3"></A></PRE></DIV><PCLASS="para"></P></DIV><DIVCLASS="htmlnav"><P></P><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch07_22.htm"TITLE="7.21. Program: netlock"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 7.21. Program: netlock"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="book"HREF="index.htm"TITLE="Perl Cookbook"><IMGSRC="../gifs/txthome.gif"ALT="Perl Cookbook"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="chapter"HREF="ch08_01.htm"TITLE="8. File Contents"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 8. File Contents"BORDER="0"></A></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228">7.21. Program: netlock</TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="index"HREF="index/index.htm"TITLE="Book Index"><IMGSRC="../gifs/index.gif"ALT="Book Index"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228">8. File Contents</TD></TR></TABLE><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><FONTSIZE="-1"></DIV<!-- LIBRARY NAV BAR --> <img src="../gifs/smnavbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links"><p> <a href="copyrght.htm">Copyright &copy; 2002</a> O'Reilly &amp; Associates. All rights reserved.</font> </p> <map name="library-map"> <area shape="rect" coords="1,0,85,94" href="../index.htm"><area shape="rect" coords="86,1,178,103" href="../lwp/index.htm"><area shape="rect" coords="180,0,265,103" href="../lperl/index.htm"><area shape="rect" coords="267,0,353,105" href="../perlnut/index.htm"><area shape="rect" coords="354,1,446,115" href="../prog/index.htm"><area shape="rect" coords="448,0,526,132" href="../tk/index.htm"><area shape="rect" coords="528,1,615,119" href="../cookbook/index.htm"><area shape="rect" coords="617,0,690,135" href="../pxml/index.htm"></map> </BODY></HTML>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -