<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Re-Cycled Air &#187; programming</title>
	<atom:link href="http://www.re-cycledair.com/tag/programming/feed" rel="self" type="application/rss+xml" />
	<link>http://www.re-cycledair.com</link>
	<description>Jack Slingerland&#039;s Programming Adventures</description>
	<lastBuildDate>Tue, 17 Jan 2012 01:14:07 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Tracking Email Open Time with PHP</title>
		<link>http://www.re-cycledair.com/tracking-email-open-time-with-php</link>
		<comments>http://www.re-cycledair.com/tracking-email-open-time-with-php#comments</comments>
		<pubDate>Tue, 01 Mar 2011 12:19:43 +0000</pubDate>
		<dc:creator>Jack Slingerland</dc:creator>
				<category><![CDATA[PHP Programming]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.re-cycledair.com/?p=1090</guid>
		<description><![CDATA[Some time ago I had great aspirations of launching a web company that does email tracking and analytics. One of the things that I really wanted to figure out but wasn&#8217;t well documented on the web was how to track &#8230; <a href="http://www.re-cycledair.com/tracking-email-open-time-with-php">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Some time ago I had great aspirations of launching a web company that does email tracking and analytics.  One of the things that I really wanted to figure out but wasn&#8217;t well documented on the web was how to track how long a user had a particular email open.  When a company like MailChimp wants to track emails that they are sending out, they put a small image in the email called a &#8220;beacon&#8221;.  When the user opens the email, the beacon image is requested from the server.  The server sends the image, but not before it gathers information about the computer requesting it.  The works great for checking if an email was opened, or what platform the person is on, but it doesn&#8217;t work at all for determining how long the email was open for.</p>
<p>One option that came to mind for checking the open time of an email was long polling.  Long polling (in this case) would use Javascript to contact the server every X seconds after the email was loaded.  Using those requests, it&#8217;d be trivial to find out how long it was open for.  Unfortunately, most (if not all) email clients don&#8217;t allow the execution of Javascript within emails, so that idea was completely sank.  The only option I had left was to use the beacon image to somehow determine open time.</p>
<p>The only option I could think of for using the image beacon without any Javascript was to redirect the image back to itself.  After much trial and error, I came up with the following.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Open the file, and send to user.</span>
<span style="color: #000088;">$fileName</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;../img/beacon.gif&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$fp</span> <span style="color: #339933;">=</span> <span style="color: #990000;">fopen</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$fileName</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;r&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Content-type: image/gif&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #990000;">feof</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$fp</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">//Do a redirect for the timing.?</span>
    <span style="color: #990000;">sleep</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_GET</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'clientID'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    	<span style="color: #000088;">$redirect</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$_SERVER</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'REQUEST_URI'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
    	<span style="color: #000088;">$redirect</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$_SERVER</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'REQUEST_URI'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;?clientID=&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$clientID</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Location: <span style="color: #006699; font-weight: bold;">$redirect</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>So what&#8217;s happening in this code?  First of all, we&#8217;re opening a small GIF file that we&#8217;re going to pretend to send to the user.  The second step is to send a header for an image file to the user so that their mail client expects one to be delivered.  This step is important because if the header isn&#8217;t sent, the browser/mail client will close the connection.  After that, you make the request sleep for a few seconds (as few or as many as you want depending on how granular you want your timing data to be) and then redirect back to the same page.  The &#8220;if&#8221; statement within the while loop is there so you can identify incoming requests and log the data accordingly.</p>
<p>So there you have it.  If you&#8217;ve ever wondered how people track the open time of an email, it&#8217;s probably a method very similar to this.  The only caveat to this method is that it relies on the user loading images in an email.  However, if you have a large enough sample you can just take the average open time from the users that did open it and be fairly confident with that.</p>
<p>&nbsp;</p>
<h3>If you liked this article, then you may like:</h3>
<li><a href="http://www.re-cycledair.com/php-dark-arts-multi-threading-part-1">PHP Dark Arts: Multi-Processing (Part 1)</a></li>
<li><a href="http://www.re-cycledair.com/php-dark-arts-multi-processing-part-2">PHP Dark Arts: Multi-Processing (Part 2)</a></li>
<li><a href="http://www.re-cycledair.com/php-dark-arts-shared-memory-segments-ipc">PHP Dark Arts: Shared Memory Segments (IPC)</a></li>
<li><a href="http://www.re-cycledair.com/php-dark-arts-semaphores">PHP Dark Arts: Semaphores</a></li>
<li><a href="http://www.re-cycledair.com/php-dark-arts-gui-programming-with-gtk">PHP Dark Arts: GUI Programming with GTK</a></li>
<li><a href="http://www.re-cycledair.com/php-dark-arts-sockets">PHP Dark Arts: Sockets</a></li>
<li><a href="http://www.re-cycledair.com/php-dark-arts-daemonizing-a-process">PHP Dark Arts: Daemonizing a Process</a></li>
 <img src="http://www.re-cycledair.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1090" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.re-cycledair.com/tracking-email-open-time-with-php/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>CoffeeScript with WebSQL and jQuery</title>
		<link>http://www.re-cycledair.com/coffeescript-with-websql-and-jquery</link>
		<comments>http://www.re-cycledair.com/coffeescript-with-websql-and-jquery#comments</comments>
		<pubDate>Wed, 29 Dec 2010 12:52:52 +0000</pubDate>
		<dc:creator>Jack Slingerland</dc:creator>
				<category><![CDATA[Other Programming]]></category>
		<category><![CDATA[coffeescript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[websql]]></category>

		<guid isPermaLink="false">http://www.re-cycledair.com/?p=1018</guid>
		<description><![CDATA[Lately I&#8217;ve developed a distaste for Javascript.  I like what Javascript has done for the web, but I hate the syntax.  I hate that there are little &#8220;Gotch Ya!&#8221;&#8216;s all over the language.  I don&#8217;t have to worry about that &#8230; <a href="http://www.re-cycledair.com/coffeescript-with-websql-and-jquery">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Lately I&#8217;ve developed a distaste for Javascript.  I like what Javascript has done for the web, but I hate the syntax.  I hate that there are little &#8220;Gotch Ya!&#8221;&#8216;s all over the language.  I don&#8217;t have to worry about that too much anymore though since I&#8217;ve started using CoffeeScript.  If you interested in learning more about it, check out the <a href="http://jashkenas.github.com/coffee-script/">official web site</a>, and then my &#8220;<a href="http://www.re-cycledair.com/getting-started-with-coffeescript">Getting Started</a>&#8221; guide.</p>
<p>Now that I&#8217;ve had a chance to dive in to CoffeeScript a bit more, I&#8217;ve started to integrate what I&#8217;m doing with other features and libraries to see what I can create.  For work I&#8217;ve been using a lot of WebSQL and jQuery, so that was the first place I took my new found CoffeeScript powers to.</p>
<p>Using jQuery with CoffeeScript is really, <span style="text-decoration: underline"><strong>really</strong></span>, easy.  For instance, let&#8217;s say we want to Ajax a page into an array:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$.<span style="color: #660066;">get</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;mypage.html&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>
    myArray.<span style="color: #660066;">push</span> data
<span style="color: #009900;">&#41;</span></pre></div></div>

<p>The syntax changes just a hair, but overall it looks a lot cleaner.</p>
<p>As mentioned previously, the other thing I&#8217;ve been doing a lot at work recently was working with WebSQL.  It&#8217;s been dropped by the W3C, but Webkit has implemented it already so it&#8217;s here to stay.  Anyways, CoffeeScript makes WebSQL a little more palatable.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">#Start a transaction
db.<span style="color: #660066;">transaction</span><span style="color: #009900;">&#40;</span> <span style="color: #009900;">&#40;</span>tx<span style="color: #009900;">&#41;</span> <span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>
    query <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;SELECT * FROM table&quot;</span>
    tx.<span style="color: #660066;">executeSql</span><span style="color: #009900;">&#40;</span>query<span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#40;</span>tx<span style="color: #339933;">,</span> results<span style="color: #009900;">&#41;</span> <span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>
        rLength <span style="color: #339933;">=</span> results.<span style="color: #660066;">rows</span>.<span style="color: #660066;">length</span>
        <span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">=</span><span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> rLength<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
            <span style="color: #000066;">alert</span> results.<span style="color: #660066;">rows</span>.<span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">someColName</span>
    <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#41;</span></pre></div></div>

<p>With WebSQL and CoffeeScript, the syntax doesn&#8217;t change a ton, but I like the look of it better without the braces.</p>
<p>Another feature that I wanted to share with out about CoffeeScript is it&#8217;s equivalent to PHP&#8217;s key, value loop construct.  In PHP, it would look like:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$key</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000088;">$value</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$myArray</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">//do stuff</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>In CoffeeScript, the equivalent is:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">for</span> own key<span style="color: #339933;">,</span> value of myArray
    #Do stuff.</pre></div></div>

<p>The benefit of the CoffeeScript version is that it can loop over object properties as well, not just arrays.  If you have any other cool features or examples of CoffeeScript usage, drop a link (or example) into the comments.</p>
 <img src="http://www.re-cycledair.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1018" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.re-cycledair.com/coffeescript-with-websql-and-jquery/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>My History of Failure</title>
		<link>http://www.re-cycledair.com/failure</link>
		<comments>http://www.re-cycledair.com/failure#comments</comments>
		<pubDate>Sun, 12 Dec 2010 06:06:26 +0000</pubDate>
		<dc:creator>Jack Slingerland</dc:creator>
				<category><![CDATA[Other]]></category>
		<category><![CDATA[failure]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[startup]]></category>

		<guid isPermaLink="false">http://www.re-cycledair.com/?p=995</guid>
		<description><![CDATA[&#8220;I&#8217;ve failed over and over and over again in my life, and that is why I succeed.&#8221; This is my third attempt.  I&#8217;ve tried twice before and failed, but this time could be different.  It could end up in failure &#8230; <a href="http://www.re-cycledair.com/failure">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><em>&#8220;I&#8217;ve failed over and over and over again in my life, and that is why I succeed.&#8221;</em></p>
<p>This is my third attempt.  I&#8217;ve tried twice before and failed, but this time could be different.  It could end up in failure just like the others, but I don&#8217;t think it will.  I&#8217;m smarter this time around.  I&#8217;ve learned from my mistakes, am better at what I do, and I have more to lose.</p>
<h2>Encode4Free</h2>
<p>The first time around was in 2007.  I had just learned PHP and thought I had what it took to make a video encoding startup.  This was before the term &#8220;cloud&#8221; was popular, and my idea was that users would upload videos to my service, encode them into whatever format they liked, and then re-download them.  For revenue, I thought that a free service could be done by adding advertising to the beginning of the encoded video.  Or, a user could pay small fee to get moved to the front of the queue and have no advertisements.</p>
<p>The idea seemed good, but I wasn&#8217;t dedicated to it.  I got a design going and had the back-end encoding stuff working, but I just couldn&#8217;t act on it.  Some other things went wrong too.</p>
<ul>
<li>No motivation &#8211; I was still in college, didn&#8217;t need the money, and enjoyed my life just where it was.  There wasn&#8217;t really a huge motivation for me to do this.</li>
<li>No passion &#8211; I honestly didn&#8217;t care about video encoding.  Sure it&#8217;s cool, but only cool from a technical standpoint.  It wasn&#8217;t something I could really get behind.</li>
<li>Knowledge &#8211; I really had no idea how deep the programming rabbit hole went at this point.  Not knowing what good design was really put a cramp in how fast I could develop too.  In short, I was inexperienced and it showed.</li>
<li>Flawed business model &#8211; In retrospect, this should have been a freemium model.  10 minute video for free, anything over is charged.  That way people don&#8217;t get annoying advertisements added to their videos.</li>
</ul>
<h2>Should I Get The Book?</h2>
<p>In 2008 and early 2009 I worked on &#8220;Should I Get The Book?&#8221;(SIGTB).  As a grad student reflecting on my undergraduate years, I realized that I spent a ridiculous amount of money on books that I never needed.  After talking to friends and classmates, it seemed this was a universal problem, and my startup idea was born.  This time, I did things right (sort of).  I took a few hours every week over the the summer and started hacking away at it.  By the end of the summer, I had a functioning product.  I did a launch, and the waited.  But nobody came.</p>
<p>So what happened?  Was it competition?  Was it a poor idea?  Well, it was a lot of things.</p>
<ul>
<li>Design &#8211; This is huge.  My site design sucked.  I basically ripped off a WordPress template that somebody made because it looked cool.  It had nothing to do with my idea, and it showed.  People coming to the page would say &#8220;So what is this about?&#8221;.</li>
<li>UI &#8211; The interface and experience was awful.  None of it made sense, and the changes that people did suggest I back-burnered until I &#8220;had more time&#8221;.</li>
<li>Seed Data &#8211; The idea that users leave reviews about whether they needed the book or not was great, except that nobody would do it.  Without having some reviews already in there, I found that people weren&#8217;t motivated to leave a review because they thought the site wasn&#8217;t being used.  I needed to have data seeded, but I couldn&#8217;t think of a good way to do this without paying any money (I had none at the time).</li>
<li>Focus &#8211; I tried to focus on too many schools at once with the first launch.  I should have started with one to see if the concept would stick.</li>
<li>Advertising &#8211; On a college campus, flyers and word of mouth is key.  I had zero flyers and nobody talking about me.</li>
<li>Karma &#8211; Users like getting a reward for doing something.  It doesn&#8217;t have to be money, karma works just as well.  Users get to scratch their competitive urge by posting reviews, getting karma, and checking to see if they have more then their friends. I should have done this, but didn&#8217;t.</li>
<li>Evergreen data &#8211; One of the big problems with this data is that the instructor can change books, change styles, or even stop teaching.  The data can become useless quickly.</li>
</ul>
<p>Once I realized most of these things I vowed to start a re-design with all of these issues addressed.  I was about 25% of the way through the mock-up when I was informed that <a href="http://www.ratemyprofessor.com">RateMyProfessor.com</a> had a similar feature.  It was easy to use, and they already had a huge user base.  My idea was basically sunk.</p>
<p>While SIGTB flopped, it was important step for me.  I had pushed a project through to completion, learned a lot about marketing, and learned that I really need a co-founder to talk me out of bad ideas.  Most importantly though, I proved to myself that I could accomplish something.  I might have given up too quickly, but I think that the idea wouldn&#8217;t have worked well anyways.</p>
<h2>CampaignAlytics (Working Name)</h2>
<p>I started this idea out in late October of this year.  The idea is that email campaign analytics can be done better.  Currently analytics is rolled in as a feature for big mailers (Mail Chimp, etc), but it doesn&#8217;t provide the in-depth analytics that a lot of marketing folks are looking for.  We&#8217;re looking to change that.  I&#8217;ve been working for an hour a day since November 1st, and have a lot to show for it.  I pitched the idea to a local pitch night, and the reception was great.  We have a lot of great features, and do it all in a non-obtrusive way that is compatible with mailing services, or can be rolled into your custom solution using our API.</p>
<p>I&#8217;m taking a different path with this startup, based on the things I&#8217;ve learned on the last two.</p>
<ul>
<li>Pay for a design &#8211; The first thing I did for this web app was pay for a design.  I got a great deal, and now have a design that I can be proud of and shows off the product like nothing I could have ever come up with.</li>
<li>Co-Founder &#8211; Having someone to talk you out of bad ideas, and give you a sense of perspective is amazing.  Having someone to discuss ideas with and share the burden is pretty great too.</li>
<li>Funding &#8211; I&#8217;ve come to the conclusion that without a little bit of funding, this startup will take forever to complete.  We&#8217;re applying to the seed incubator <a href="http://www.momentum-mi.com/">Momentum</a> and hopefully we&#8217;ll get funded.</li>
<li>Iterate &#8211; I&#8217;ve already gone through two different layouts and menu structures for the account/analytics page.  The second version is far better than the first because I asked for feedback from a few trusted people and implemented the changes right away.</li>
</ul>
<p>The thing I hope you can take away from this is that you are going to fail many times before you succeed.  Being persistent (and maybe a bit stubborn) will take you 70% of the way there, and the rest is on how good your idea is.</p>
 <img src="http://www.re-cycledair.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=995" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.re-cycledair.com/failure/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>PHP Bitwise Operations</title>
		<link>http://www.re-cycledair.com/php-bitwise-operations</link>
		<comments>http://www.re-cycledair.com/php-bitwise-operations#comments</comments>
		<pubDate>Wed, 03 Nov 2010 23:49:50 +0000</pubDate>
		<dc:creator>Jack Slingerland</dc:creator>
				<category><![CDATA[PHP Programming]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[bitwise]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.re-cycledair.com/?p=948</guid>
		<description><![CDATA[A bitwise operation is an operation that works on the individual bits of a number.  Yes, that means the binary(base 2) representation of a number.  These bitwise operations work by exploiting properties of binary numbers to their advantage.  For instance, &#8230; <a href="http://www.re-cycledair.com/php-bitwise-operations">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>A bitwise operation is an operation that works on the individual bits of a number.  Yes, that means the binary(base 2) representation of a number.  These bitwise operations work by exploiting properties of binary numbers to their advantage.  For instance, if the binary representation of a number ends with a 1, it&#8217;s odd.</p>
<h2>Base 2 Refresher</h2>
<p>For those of us who don&#8217;t manipulate bits every day (including myself), I thought that a quick refresher on binary representation would be a good idea.  First, let&#8217;s create a table.</p>
<table style="width: 241px; height: 41px;" border="0">
<tbody>
<tr style="text-align: center;">
<td><strong>4</strong></td>
<td><strong>3</strong></td>
<td><strong>2</strong></td>
<td><strong>1</strong></td>
<td><strong>0</strong></td>
</tr>
<tr style="text-align: center;">
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
</tbody>
</table>
<div>
<p>Each column in the table represents a power of 2.  The first column (from the right) represents 2<sup>0</sup>, the second 2<sup>1</sup>, and so on.  Notice that I have a 1 in the row below the 0 column.  That stands for 2<sup>0</sup>, and 2<sup>0</sup> is equal to 1.  Therefore, the number represented above (00001) is equal to 1.  On to the next table.</p>
</div>
<table style="width: 241px; height: 41px;" border="0">
<tbody>
<tr style="text-align: center;">
<td><strong>4</strong></td>
<td><strong>3</strong></td>
<td><strong>2</strong></td>
<td><strong>1</strong></td>
<td><strong>0</strong></td>
</tr>
<tr style="text-align: center;">
<td>0</td>
<td>0</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
<div>﻿﻿Now the base-2 number in the bottom row is 00111.  This is equal to 2<sup>2</sup> + 2<sup>1</sup> + 2<sup>0</sup>, or 4 + 2 + 1, which is equal to 7.  As you can see, using binary representation is pretty easy.  On to our final example.</div>
<table style="width: 241px; height: 41px;" border="0">
<tbody>
<tr style="text-align: center;">
<td><strong>4</strong></td>
<td><strong>3</strong></td>
<td><strong>2</strong></td>
<td><strong>1</strong></td>
<td><strong>0</strong></td>
</tr>
<tr style="text-align: center;">
<td>1</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
</tbody>
</table>
<div>This example a bit (har, har) trickier.  The base-2 number in the bottom row is 11001, which is  2<sup>4</sup> + 2<sup>3 </sup>+2<sup>0</sup>(16 + 8 + 1) = 25.  Notice if there are zeros in the columns, we just ignore them completely.</div>
<div>And that&#8217;s it!  Base-2 representation of numbers is easy, and critical for every programmer to understand.  Now on to some tricks.</div>
<h2>Trick 1 : Odd / Even</h2>
<p>One of the most useful bitwise tricks for web developers is for determining if a number is even or odd.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$i</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">10</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span><span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$i</span> <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
          <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;This is odd.&quot;</span><span style="color: #339933;">;</span>
     <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
          <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;This is even.&quot;</span><span style="color: #339933;">;</span>
     <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<div>So how does help your web development?  Alternating rows.  If you deal with data in a tabular format, you nearly always need to alternate row color on a table.  Using the bitwise &#8220;AND&#8221; operator is a good way to accomplish this.</div>
<h2>Trick 2 : Multiplication and Division</h2>
<div>Using the left-shift (&lt;&lt;) and right-shift (&gt;&gt;) operators, we can easily divide and multiple by powers of two.  These operators aren&#8217;t limited to powers of two, but it makes things easier to understand.</div>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Example 1</span>
<span style="color: #000088;">$x</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$x</span> <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;&amp;</span>lt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//4</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$x</span> <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;&amp;</span>lt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//8</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Example 2</span>
<span style="color: #000088;">$x</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">16</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$x</span> <span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//8</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$x</span> <span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//4</span></pre></div></div>

<p>In example 1, we left shift the number 2 one place.  By left shifting 1 place, it&#8217;s the same as multiplying that number by 2.  By left shifting 2 places, it&#8217;s the same multiplying the number by 2 twice.</p>
<p>Example 2 is doing bitwise division.  Right shifting by 1 place is the same as dividing the number by 2.  Right shifting by 2 places, is the same is the same as dividing the number by 2 twice.</p>
<h2>Others</h2>
<p>There are most definitely a ton of other uses for bitwise operators, however these are the ones I use the most.  If you happen to have a favorite, please let everyone know about it in the comments.</p>
<p>For a more in depth introduction to bitwise operations please check out <a href="http://en.wikipedia.org/wiki/Bitwise_operation">http://en.wikipedia.org/wiki/Bitwise_operation</a> and <a href="http://www.litfuel.net/tutorials/bitwise.htm">http://www.litfuel.net/tutorials/bitwise.htm</a></p>
 <img src="http://www.re-cycledair.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=948" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.re-cycledair.com/php-bitwise-operations/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>PHP Dark Arts: Daemonizing a Process</title>
		<link>http://www.re-cycledair.com/php-dark-arts-daemonizing-a-process</link>
		<comments>http://www.re-cycledair.com/php-dark-arts-daemonizing-a-process#comments</comments>
		<pubDate>Tue, 26 Oct 2010 23:45:41 +0000</pubDate>
		<dc:creator>Jack Slingerland</dc:creator>
				<category><![CDATA[PHP Programming]]></category>
		<category><![CDATA[daemons]]></category>
		<category><![CDATA[dark arts]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.re-cycledair.com/?p=937</guid>
		<description><![CDATA[Note:  Full source code for the example can be downloaded here. One of the many things you don&#8217;t often do with PHP (actually, I&#8217;m not sure you do this much with any language) is daemonize a process.  A daemon is &#8230; <a href="http://www.re-cycledair.com/php-dark-arts-daemonizing-a-process">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><em>Note:  Full source code for the example can be downloaded <a href="http://www.re-cycledair.com/wp-content/uploads/2010/10/daemon.zip">here</a>.</em></p>
<p>One of the many things you don&#8217;t often do with PHP (actually, I&#8217;m not sure you do this much with <span style="text-decoration: underline">any</span> language) is daemonize a process.  A daemon is program that runs in the background (read more <a href="http://en.wikipedia.org/wiki/Daemon_%28computer_software%29">here</a>).  On Unix systems, processes are usually created by forking the init process and then manipulating the process to your liking.  To create a daemon though, you need to get the init process to adopt your process.  To do that, as soon as you fork the parent process, you kill the parent.  Since you child process is parent-less, the init process generally adopts it.  Once that happens, your process has been daemonized.</p>
<h2>What You Need To Know</h2>
<p>In order to follow the example, you&#8217;ll probably want to read up on <a href="http://www.re-cycledair.com/php-dark-arts-multi-threading-part-1">multi</a>-<a href="http://www.re-cycledair.com/php-dark-arts-multi-processing-part-2">processing</a> in PHP and using <a href="http://www.php.net/manual/en/book.posix.php">POSIX</a> in PHP.  Aside from that, keep an open mind.  There are probably better ways to do this (<a href="http://nanoserv.si.kz">Nanoserv</a>), but I think that doing it manually is a great way to learn more about systems programming and PHP.</p>
<h2>Step 1:  Fork It</h2>
<p>The first thing that you need to do when daemonizing a process in PHP is fork the process.  After that, we promptly kill the parent process so that the child process can be adopted.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Set the ticks</span>
<span style="color: #000000; font-weight: bold;">declare</span><span style="color: #009900;">&#40;</span>ticks <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Fork the current process</span>
<span style="color: #000088;">$processID</span> <span style="color: #339933;">=</span> pcntl_fork<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Check to make sure the forked ok.</span>
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$processID</span> <span style="color: #339933;">==</span> <span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span> Error:  The process failed to fork. <span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$processID</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">//This is the parent process.</span>
	<span style="color: #990000;">exit</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">//We're now in the child process.</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h2>Step 2:  Detach It</h2>
<p>Now that we have successfully forked the process and killed the parent, we need to detach the process from the terminal window.  We do this so that when the terminal window closes, our process doesn&#8217;t close with it.  Once that&#8217;s done, we get our processes&#8217; id.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Now, we detach from the terminal window, so that we stay alive when</span>
<span style="color: #666666; font-style: italic;">//it is closed.</span>
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #990000;">posix_setsid</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span> Error: Unable to detach from the terminal window. <span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Get out process id now that we've detached from the window.</span>
<span style="color: #000088;">$posixProcessID</span> <span style="color: #339933;">=</span> <span style="color: #990000;">posix_getpid</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<h2>Step 3:  /var/run</h2>
<p>Now that we have our processes&#8217; id, we need to let the system know about it.  To do this, we create a file in /var/run.  This file can be named anything you want, just make sure that it&#8217;s unique and it ends with the .pid extension.  In that file, we place the pid of our process and that&#8217;s it.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Create a new file with the process id in it.</span>
<span style="color: #000088;">$filePointer</span> <span style="color: #339933;">=</span> <span style="color: #990000;">fopen</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;/var/run/phpprocess.pid&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;w&quot;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">fwrite</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filePointer</span> <span style="color: #339933;">,</span> <span style="color: #000088;">$posixProcessID</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">fclose</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filePointer</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<h2>Step 4:  Do Something</h2>
<p>Now that all the hard stuff is done, you can get to work.  What do you want your process to do?  For this example, I have mine adding 1 + 1 every 10 seconds.  Nothing too difficult, but you can make your process do whatever you like.  For instance, you could <a href="http://www.re-cycledair.com/php-dark-arts-sockets">set up a server</a> of some sort.  Note that this the code is sitting in an infinite while loop.  This is done so that the process doesn&#8217;t exit naturally.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Now, do something forever.</span>
<span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$x</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1</span> <span style="color: #339933;">+</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
	<span style="color: #990000;">sleep</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">10</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h2>Step 5:  Run It</h2>
<p>To run this process as a daemon, all you need to do is save you file and run <em>php &lt;myfile&gt;.php</em>.  You may need to execute it as a super user depending on how you permissions are set up.  Once it&#8217;s run, you can check out the results of your hard work by running <em>ps aux | less</em>.  Scroll to the bottom and your process should be there.  In the screen shot below, mine is 3rd from the bottom.</p>
<p><a href="http://www.re-cycledair.com/wp-content/uploads/2010/10/processes.png" rel="lightbox[937]"><img class="aligncenter size-full wp-image-939" src="http://www.re-cycledair.com/wp-content/uploads/2010/10/processes.png" alt="Daemonizing a Process" width="540" height="380" /></a><em>Note:  Full source code for the example can be downloaded <a href="../wp-content/uploads/2010/10/daemon.zip">here</a>.</em></p>
<h2>Did you like this article?  Check out the rest of the Dark Arts.</h2>
<ul>
<li><a href="../php-dark-arts-multi-threading-part-1">PHP Dark Arts: Multi-Processing (Part 1)</a></li>
<li><a href="../php-dark-arts-multi-processing-part-2">PHP Dark Arts: Multi-Processing (Part 2)</a></li>
<li><a href="../php-dark-arts-shared-memory-segments-ipc">PHP Dark Arts: Shared Memory Segments (IPC)</a></li>
<li><a href="../php-dark-arts-semaphores">PHP Dark Arts: Semaphores</a></li>
<li><a href="../php-dark-arts-gui-programming-with-gtk">PHP Dark Arts: GUI Programming with GTK</a></li>
<li><a href="../php-dark-arts-sockets">PHP Dark Arts: Sockets</a></li>
</ul>
 <img src="http://www.re-cycledair.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=937" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.re-cycledair.com/php-dark-arts-daemonizing-a-process/feed</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Document Your Code</title>
		<link>http://www.re-cycledair.com/document-your-code</link>
		<comments>http://www.re-cycledair.com/document-your-code#comments</comments>
		<pubDate>Mon, 04 Oct 2010 15:30:15 +0000</pubDate>
		<dc:creator>Jack Slingerland</dc:creator>
				<category><![CDATA[PHP Programming]]></category>
		<category><![CDATA[documentation]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.re-cycledair.com/?p=820</guid>
		<description><![CDATA[When you started learning to program, documenting your code was the last thing on your mind. You&#8217;re were here to learn, and learn is what you did. As your programs started to grow in complexity, your college professors preached to &#8230; <a href="http://www.re-cycledair.com/document-your-code">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>When you started learning to program, documenting your code was the last thing on your mind.  You&#8217;re were here to learn, and learn is what you did.  As your programs started to grow in complexity, your college professors preached to you &#8220;You must document your code!  What if you have to come back to it in 6 months?  Will you remember how everything works?&#8221;.  So, you dutifully documented your code.  But then something strange happened: you got a job.  In the real world there are deadlines, and that extra minute you should have taken to document the code is gone.  But the thing is, you MUST document your code.  If not for you, do it for me.  Because guess what, I&#8217;m the one that has to go in and fix it, and knowing what&#8217;s going on would make my life a lot easier.</p>
<h2>A Story</h2>
<p>When I started my current job, one of the other programmers was assigned to get me up to speed with our CMS.  My first question was &#8220;Is there any documentation I can go over?&#8221;, to which he responded &#8220;Nah, just dive in and you&#8217;ll be fine.&#8221;.  So I dove in and it only got worse from there.  As I looked through the code, nothing was documented.  Nothing!  I spent the next 3 months sifting through code trying to figure out how it all works.  I eventually did figure it all out, but it was 3 months where I was working at maybe 50%-60% of my maximum efficiency.  Having any sort of documentation would have made this process much easier.  Not only that, but because of the lack of documentation we constantly create duplicate functionality.  After all, how are you supposed to know what functionality exists if there no documentation on it?</p>
<p>Now that I&#8217;ve been at my current job awhile, I&#8217;ve decided to change things.  I&#8217;ve started taking 15 to 30 minutes a day to document our CMS using the PHPDoc format.  It may or may not catch on with the rest of the programmers, but I know that every function and class that I write has full documentation, and it feels good when the documentation gets generated with PHPDoc.  I believe the quote is &#8220;You need to be the change you believe in&#8221;.</p>
<h2>How to Document Your Code</h2>
<p>It&#8217;s easy.  Really easy actually.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #009933; font-style: italic;">/**
* Function short description
*
* This is a long description of the function.  Discuss what this function does in
* any detail that is necessary.
*
* @global void $globalVariable
* @param int $aParameter This is the description of the parameter.
* @param mixed $bParameter This is the description of another parameter.
* @return bool This is a description of the return variable.
* @todo Does something need to be done?  Put it here.
*/</span>
<span style="color: #000000; font-weight: bold;">function</span> my_function<span style="color: #009900;">&#40;</span><span style="color: #000088;">$aParameter</span><span style="color: #339933;">,</span> <span style="color: #000088;">$bParameter</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #000000; font-weight: bold;">global</span> <span style="color: #000088;">$globalVariable</span><span style="color: #339933;">;</span>
&nbsp;
     <span style="color: #666666; font-style: italic;">//If you are doing something extra complicated, make a comment inside the</span>
     <span style="color: #666666; font-style: italic;">//function.  Otherwise, you code should speak for itself.</span>
     <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$i</span><span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">20</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span><span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
          <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$i</span><span style="color: #339933;">;</span>
     <span style="color: #009900;">&#125;</span>
&nbsp;
     <span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>That&#8217;s it.  That&#8217;s all you need to get started documenting PHP code.  There&#8217;s a lot more you could be doing, but it&#8217;s not all that important.  So long as you document the parameters, the return type, and write a description about what the function does, you have the important bits.</p>
<p>So next time you think to yourself &#8220;I&#8217;ll document it later.&#8221;, just take the time to do it now.  Because guess what?  You aren&#8217;t going to go back.  Something else is going to come up, and then the rest of us will suffer.</p>
 <img src="http://www.re-cycledair.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=820" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.re-cycledair.com/document-your-code/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>PHP: Echo Versus Print(f)</title>
		<link>http://www.re-cycledair.com/php-echo-versus-printf</link>
		<comments>http://www.re-cycledair.com/php-echo-versus-printf#comments</comments>
		<pubDate>Sun, 03 Oct 2010 07:53:52 +0000</pubDate>
		<dc:creator>Jack Slingerland</dc:creator>
				<category><![CDATA[PHP Programming]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.re-cycledair.com/?p=815</guid>
		<description><![CDATA[One of the things I remember about when I started programming in PHP was the confusion I ran in to when deciding how to print text.  Should I use the print construct?  Or maybe I should use the echo construct?  &#8230; <a href="http://www.re-cycledair.com/php-echo-versus-printf">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>One of the things I remember about when I started programming in PHP was the confusion I ran in to when deciding how to print text.  Should I use the <em>print</em> construct?  Or maybe I should use the <em>echo</em> construct?  Perhaps the C-style <em>printf</em> function instead?  Eventually most people just latch on to the <em>echo</em> construct because &#8220;That&#8217;s what everyone else is doing&#8221;.  Is that the fastest method to use though? Well, that&#8217;s what I&#8217;m going to find out.</p>
<h2>The Test</h2>
<p>The test I decided to use loops 1000 times, and inside the main loop, there is a sub-loop creating the output which runs from 0 to N (where N is the value of the outer-loop counter).</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$start</span> <span style="color: #339933;">=</span> <span style="color: #990000;">microtime</span><span style="color: #009900;">&#40;</span><span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$i</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">&lt;</span> <span style="color: #cc66cc;">1000</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span><span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$x</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> <span style="color: #000088;">$x</span> <span style="color: #339933;">&lt;</span> <span style="color: #000088;">$i</span><span style="color: #339933;">;</span> <span style="color: #000088;">$x</span><span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
          <span style="color: #666666; font-style: italic;">//Output here.</span>
     <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000088;">$end</span> <span style="color: #339933;">=</span> <span style="color: #990000;">microtime</span><span style="color: #009900;">&#40;</span><span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>After the test has been completed, I just wrote the times to a text file for collection later.</p>
<h2>The Results</h2>
<ul>
<li><strong>echo</strong> &#8211; 16.470 seconds</li>
<li><strong>print</strong> &#8211; 16.473 seconds</li>
<li><strong>printf</strong> &#8211; 16.432 seconds</li>
</ul>
<p>As I expected, the difference between <em>print</em> and <em>echo</em> were negligible.  I suspect that they use the same underlying code.  The real surprise was from <em>printf()</em>, which is a function and<strong> </strong>is supposed to have taken longer because of the overhead of calling it.  I&#8217;m at a loss as to why it&#8217;s faster than the other two, but the difference isn&#8217;t really significant enough to worry about.  If someone wanted to be a bit more scientific about this, this program should be run probably a couple thousand times so that we can get a good sample and see what happens then.</p>
<p>If you would like to run this code yourself and let me know your results, it&#8217;s available for download <a href="http://www.re-cycledair.com/wp-content/uploads/2010/10/echo_vs_printf.zip">here</a>.</p>
 <img src="http://www.re-cycledair.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=815" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.re-cycledair.com/php-echo-versus-printf/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>PHP Dark Arts: Shared Memory Segments (IPC)</title>
		<link>http://www.re-cycledair.com/php-dark-arts-shared-memory-segments-ipc</link>
		<comments>http://www.re-cycledair.com/php-dark-arts-shared-memory-segments-ipc#comments</comments>
		<pubDate>Wed, 29 Sep 2010 00:40:14 +0000</pubDate>
		<dc:creator>Jack Slingerland</dc:creator>
				<category><![CDATA[PHP Programming]]></category>
		<category><![CDATA[dark arts]]></category>
		<category><![CDATA[ipc]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[shared memory]]></category>

		<guid isPermaLink="false">http://www.re-cycledair.com/?p=780</guid>
		<description><![CDATA[Note: The full source code for the examples can be downloaded here. In my previous articles on using PHP for multi-process programming, we kept it very simple.  By simple, I mean we didn&#8217;t have any inter-process communication (IPC).  IPC is &#8230; <a href="http://www.re-cycledair.com/php-dark-arts-shared-memory-segments-ipc">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><em>Note: The full source code for the examples can be downloaded </em><a href="../wp-content/uploads/2010/09/shared_memory.zip"><em>here</em>.</a></p>
<p>In my <a href="http://www.re-cycledair.com/php-dark-arts-multi-threading-part-1">previous</a> <a href="http://www.re-cycledair.com/php-dark-arts-multi-processing-part-2">articles</a> on using PHP for multi-process programming, we kept it very simple.  By simple, I mean we didn&#8217;t have any inter-process communication (IPC).  IPC is a set of techniques for the exchange of data amongst separate processes and/or threads.  There are many different ways to set up IPC, such as files, signals, sockets, pipes, semaphores, shared memory, and message passing.  This time around, we&#8217;re going to cover PHP&#8217;s implementation of shared memory segments.</p>
<p>So what does it mean to share a memory segment?  It means that the program will create a section of memory that can be accessed by other processes on the system.  Normally this isn&#8217;t the case, since most processes have mutually exclusive address spaces.  The benefit of using a shared memory segment is that communication between processes is extremely fast.  The main downside is that processes must be running on the same machine (and same processor in some cases), where as other types of IPC can be used over a network.</p>
<h2>Creating a Shared Memory Segment</h2>
<p>In order to share memory between processes, you first need to create the shared memory segment.  This is accomplished with PHP&#8217;s <a href="http://www.php.net/manual/en/function.shm-attach.php"><em>shm_attach()</em></a> function.  The <em><a href="http://www.php.net/manual/en/function.shm-attach.php">shm_attach()</a></em> function takes 3 parameters.</p>
<ul>
<li><strong>$key (int)</strong> &#8211; This is an integer value that identifies your shared memory segment.  If you used 123456 for this value in one process, you would need to use the same key in another process to access the shared memory segment.<strong><br />
</strong></li>
<li><strong>$memsize (int)</strong> -  This is the amount of memory (in bytes) you would like to share.  Deciding how large this should be is sort of a pain.  The easiest way it to simply pick an arbitrary amount and make sure anything you try to share isn&#8217;t larger then that.  The best way would be to know the maximum size of data you will need to share and set it to that value.</li>
<li><strong>$perm (int)</strong> &#8211; The permissions for the shared memory segment.  These permissions follow typical Unix style permissions.  The default is <em>0666</em> which means that everyone can read from and write to this memory segment.</li>
</ul>
<p>On success, <em><a href="http://www.php.net/manual/en/function.shm-attach.php">shm_attach()</a></em> returns an identifier of the shared memory segment.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Define shared memory segment properties.</span>
<span style="color: #000088;">$key</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;987654&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$permissions</span> <span style="color: #339933;">=</span> <span style="color: #208080;">0666</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$size</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1024</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Create or open the shared memory segment.</span>
<span style="color: #000088;">$segment</span> <span style="color: #339933;">=</span> <span style="color: #990000;">shm_attach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$key</span><span style="color: #339933;">,</span> <span style="color: #000088;">$size</span><span style="color: #339933;">,</span> <span style="color: #000088;">$permissions</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<h2>Using Your Shared Memory Segment</h2>
<p>Now that you have created a shared memory segment, you&#8217;ll obviously want to try it out.  Using it is pretty straight forward with the <em><a href="http://www.php.net/manual/en/function.shm-put-var.php">shm_put_var()</a> </em> and <a href="http://www.php.net/manual/en/function.shm-get-var.php"><em>shm_get_var()</em></a> functions.  They work as you might expect them to.  <a href="http://www.php.net/manual/en/function.shm-put-var.php"><em>shm_put_var()</em></a> has 3 parameters:</p>
<ul>
<li>The shared memory segment key.</li>
<li>An integer used basically as an index on the data (making it easier to retrieve).</li>
<li>Some variable.  This can be anything so long as it&#8217;s smaller than the size you&#8217;ve defined the memory segment to be.</li>
</ul>
<p>The <a href="http://www.php.net/manual/en/function.shm-get-var.php"><em>shm_get_var()</em></a> function is very similar.  It only takes 2 parameters, one of which is the key for the shared memory segment, and the other is the integer value (index) associated with the stored data.  Now that you know what the functions do, let&#8217;s put it all together in a little program.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #666666; font-style: italic;">//Check the command line arguments</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$argv</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&lt;</span> <span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">echo</span>  <span style="color: #0000ff;">&quot;Usage: php shared_memory.php &lt;send|get|delete&gt; &lt;integer identifier&gt; &lt;value&gt;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
     <span style="color: #990000;">exit</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Define shared memory segment properties.</span>
<span style="color: #000088;">$key</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;987654&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$permissions</span> <span style="color: #339933;">=</span> <span style="color: #208080;">0666</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$size</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1024</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Create or open the shared memory segment.</span>
<span style="color: #000088;">$segment</span> <span style="color: #339933;">=</span> <span style="color: #990000;">shm_attach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$key</span><span style="color: #339933;">,</span> <span style="color: #000088;">$size</span><span style="color: #339933;">,</span> <span style="color: #000088;">$permissions</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Handle operations for the segment.</span>
<span style="color: #b1b100;">switch</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$argv</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">&quot;send&quot;</span><span style="color: #339933;">:</span>
          <span style="color: #990000;">shm_put_var</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$segment</span><span style="color: #339933;">,</span> <span style="color: #000088;">$argv</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$argv</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">3</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
          <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Message sent to shared memory segment.<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
          <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
     <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">&quot;get&quot;</span><span style="color: #339933;">:</span>
          <span style="color: #000088;">$data</span> <span style="color: #339933;">=</span> <span style="color: #990000;">shm_get_var</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$segment</span><span style="color: #339933;">,</span> <span style="color: #000088;">$argv</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
          <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Received data: <span style="color: #006699; font-weight: bold;">{$data}</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
          <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
     <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">&quot;delete&quot;</span><span style="color: #339933;">:</span>
          <span style="color: #990000;">shm_remove</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$segment</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
          <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Shared memory segment released.<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
          <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>A quick glance at the code reveals that I&#8217;m making this program a little interactive for easier use.  All it does is check to make sure your command line arguments are correct, creates / opens the shared memory segment, and then performs the given operation on the segment.  An example:</p>
<pre>
<->php shared_memory.php
Usage: php shared_memory.php send|get|delete integer identifier value;
<->php shared_memory.php send 1 "Hello.  This is the shared memory segment."
Message sent to shared memory segment.
<->php shared_memory.php get 1
Received data: Hello.  This is the shared memory segment.
<->php shared_memory.php delete
Shared memory segment content deleted.
</pre>
<p>You&#8217;ll also notice that at the end I delete the contents of the shared memory segment.  It&#8217;s important to understand the difference between detaching and deleting(removing) here.  When you detach the shared memory segment, it&#8217;s possible for your data to still exist in memory until it&#8217;s overwritten by something else.  This poses a big security threat, so you should <strong>always</strong> delete(remove) the data first.  So how do we release the memory?  By using the <em><a href="http://www.php.net/manual/en/function.shm-detach.php">s</a><a href="http://www.php.net/manual/en/function.shm-detach.php">hm_detach()</a></em> function.</p>
<p><-><br />
//Define shared memory segment properties.<br />
$key = &#8220;987654&#8243;;<br />
$permissions = 0666;<br />
$size = 1024;</p>
<p>//Create or open the shared memory segment.<br />
$segment = shm_attach($key, $size, $permissions);</p>
<p>//Detach the memory segment.<br />
shm_detach($segment);
</pre>
<h2>Download</h2>
<p>Now that your done, check out the full source code for the examples <a href="http://www.re-cycledair.com/wp-content/uploads/2010/09/shared_memory.zip">here</a>.  In the <span style="text-decoration: underline;"><strong>near</strong></span> future I hope to have a virtual machine available for download, so users who don't want to mess with configuration can just start it up and go.</p>
 <img src="http://www.re-cycledair.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=780" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.re-cycledair.com/php-dark-arts-shared-memory-segments-ipc/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>PHP Dark Arts: Multi-Processing (Part 2)</title>
		<link>http://www.re-cycledair.com/php-dark-arts-multi-processing-part-2</link>
		<comments>http://www.re-cycledair.com/php-dark-arts-multi-processing-part-2#comments</comments>
		<pubDate>Sat, 25 Sep 2010 02:32:48 +0000</pubDate>
		<dc:creator>Jack Slingerland</dc:creator>
				<category><![CDATA[PHP Programming]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[priority]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[signal handling]]></category>

		<guid isPermaLink="false">http://www.re-cycledair.com/?p=762</guid>
		<description><![CDATA[Note: Part 1 of this series can be found here.  Also, after feedback from the development community, this series was renamed to &#8220;Multi-Processing&#8221; instead of &#8220;Multi-Threading&#8221;.   To most people the distinction probably doesn&#8217;t matter, but this title is more &#8230; <a href="http://www.re-cycledair.com/php-dark-arts-multi-processing-part-2">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><span style="font-size: 13.3333px;"><em>Note:  Part 1 of this series can be found <a href="http://www.re-cycledair.com/php-dark-arts-multi-threading-part-1">here</a>.  Also, after feedback from the development community, this series was renamed to &#8220;Multi-Processing&#8221; instead of &#8220;Multi-Threading&#8221;.   To most people the distinction probably doesn&#8217;t matter, but this title is more accurate.</em></span></p>
<h2>Priority</h2>
<p>The priority of a process is a ranking given to it.  The higher priority the process is given, the more CPU time it will get.  How much time on the processor each process gets is determined by the scheduling algorithm that is used, but in general, higher priority processes will get more CPU time.   All this begs the question, what is process X&#8217;s priority and how can I set it?</p>
<p>When compiled with the <em>&#8211;enable-pctl</em> option, PHP gives you access to the <a href="http://php.net/manual/en/function.pcntl-getpriority.php"><em>pcntl_getpriority()</em></a> function.  This function is, well, obvious.  It gets the priority of the current process, or if a PID (Process ID) is specified, that process instead.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$priority</span> <span style="color: #339933;">=</span> pcntl_getpriority<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;This process priority is: <span style="color: #006699; font-weight: bold;">{$priority}</span>.&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$priority</span> <span style="color: #339933;">=</span> pcntl_getpriority<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1234</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Process 1234's priority is: <span style="color: #006699; font-weight: bold;">{$priority}</span>.&quot;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>So that one&#8217;s pretty easy.  Not much explaining to do there.  But what about setting process priority?  For that, we use <a href="http://www.php.net/manual/en/function.pcntl-setpriority.php"><em>pcntl_setpriority()</em></a>.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>pcntl_setpriority<span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">15</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Priority set successfully.&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Failed to set priority.&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>pcntl_setpriority<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">15</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">1234</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Priority of process 1234 set successfully.&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Failed to set priority of process 1234.&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The first parameter of this function is the priority.  In most cases, this value can range between -20 and 20.  The lower the number, the higher priority your process receives (counter-intuitive right?).  These numbers can change though, so you may want to view the man page for your operating system&#8217;s <em>setpriority(2)</em> function.  The second parameter is the process id.  If left blank, it sets the current processes priority, otherwise it tries to set the priority of the PID that is given.</p>
<h2>Signals</h2>
<p>A signal is a limited form of inter-process communication used in Unix systems.  Believe it or not, you probably use signals often when you are using a Linux box (CTRL+C anyone?).  Signals can be a problem when you&#8217;re doing important work that you don&#8217;t want interrupted, so PHP allows us to install signal handlers so that we can handle these situations gracefully.  To install a custom signal handler, you use the <a href="http://www.php.net/manual/en/function.pcntl-signal.php"><em>pcntl_signal()</em></a> function.  Calling this function isn&#8217;t as straight-forward as the others though.  The first parameter is the signal which you are intercepting, which is an integer.  Most of the signals are defined as constants(<a href="http://www.php.net/manual/en/pcntl.constants.php">here</a>), so that&#8217;s what we&#8217;ll be using.  The second parameter is a callback function to handle the signal processing.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">declare</span><span style="color: #009900;">&#40;</span>ticks <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">function</span> signal_callback<span style="color: #009900;">&#40;</span><span style="color: #000088;">$signalNumber</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">switch</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$signalNumber</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
          <span style="color: #b1b100;">case</span> SIGTERM<span style="color: #339933;">:</span>
               <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Handling shutdown tasks.&quot;</span><span style="color: #339933;">;</span>
               <span style="color: #990000;">exit</span><span style="color: #339933;">;</span>
               <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
          <span style="color: #b1b100;">case</span> SIGHUP<span style="color: #339933;">:</span>
               <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Handling restart stuff.&quot;</span><span style="color: #339933;">;</span>
               <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
          <span style="color: #b1b100;">default</span><span style="color: #339933;">:</span>
              <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Handling all other signals.&quot;</span><span style="color: #339933;">;</span>
     <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
pcntl_signal<span style="color: #009900;">&#40;</span>SIGTERM<span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;signal_callback&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
pcntl_signal<span style="color: #009900;">&#40;</span>SIGHUP<span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;signal_callback&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>The above code first declares our callback function, then has a simple switch statement to handle the different signals.  After the function is constructed, we just call <em>pcntl_signal()</em> to set up the handler.  But why would you want to handle signals in the first place?  There are many reasons, but a good example would be financial data.  Wouldn&#8217;t you want to make sure a transaction goes all the way through before the system dies?  Or perhaps you want to send a message to someone if all transactions couldn&#8217;t be completed?  It&#8217;s situations like these where handling signals makes sense.</p>
<p>Now that we know how to handle signals, there are all sorts of neat functions we can play with.  If you interested in learning more, I suggest you check out the <a href="http://www.php.net/manual/en/ref.pcntl.php">PHP documentation on the subject</a>.</p>
 <img src="http://www.re-cycledair.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=762" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.re-cycledair.com/php-dark-arts-multi-processing-part-2/feed</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>PHP Dark Arts: Multi-Processing (Part 1)</title>
		<link>http://www.re-cycledair.com/php-dark-arts-multi-threading-part-1</link>
		<comments>http://www.re-cycledair.com/php-dark-arts-multi-threading-part-1#comments</comments>
		<pubDate>Wed, 22 Sep 2010 01:09:56 +0000</pubDate>
		<dc:creator>Jack Slingerland</dc:creator>
				<category><![CDATA[PHP Programming]]></category>
		<category><![CDATA[fork]]></category>
		<category><![CDATA[multi-threading]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.re-cycledair.com/?p=752</guid>
		<description><![CDATA[Note:  Part 2 of this post can be found here. Of all the glorious programming languages in existence, you&#8217;ve chosen to work with PHP.  Okay, maybe you were forced to, but that doesn&#8217;t mean you can&#8217;t have fun right?  Hmm, &#8230; <a href="http://www.re-cycledair.com/php-dark-arts-multi-threading-part-1">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><em>Note:  Part 2 of this post can be found <a href="http://www.re-cycledair.com/php-dark-arts-multi-processing-part-2">here</a>.</em></p>
<p>Of all the glorious programming languages in existence, you&#8217;ve chosen to work with PHP.  Okay, maybe you were forced to, but that doesn&#8217;t mean you can&#8217;t have fun right?  Hmm, fun&#8230; What&#8217;s fun?  Threading, race conditions, and deadlocks.  Sounds like loads of fun!  But alas, PHP doesn&#8217;t have functionality to cover this.  True, but the host operating system does.  We can just fork processes manually like in the good &#8216;ole days and then ride off into the sunset.  But we shouldn&#8217;t do that, it&#8217;s wrong.  It&#8217;s taking advantage of PHP.  Bah! We&#8217;re going to do it anyways.  And FOR THE LOVE OF GOD, <strong><span style="text-decoration: underline;">do not</span></strong> do this in production code.  If you need multi-threading, use a different language.</p>
<h2>Process Control</h2>
<p>One of those things that you are bound to learn about if you go through a computer science degree is process control.  Process control usually comes up slowly and then bites you in the ass REALLY hard during operating systems courses.  Thinking about race conditions, deadlocks, and collisions are all part of the game.  And guess what?  When you are writing multi-threaded programs this is exactly the type of thing you will encounter.</p>
<p>When thinking about process control, people often cite some form of a producer-consumer problem.  You have one process (thread) producing information, and another thread consuming it.  For instance, a producer may spit out a stream of integers, and the consumer will, well, consume them.  However, the consumer will terminate itself when it hits a non-integer character.  That&#8217;s called out exit condition, and it&#8217;s very important.  You have to always remember to have some sort of fool-proof exit condition, otherwise the process is going to hang and go zombie on your.  If your program get&#8217;s executed a few thousand times a day, you get a few thousand zombies (process zombie apocalypse!).  So, the import part here is to remember that you need to have exit condtions.</p>
<h2>Getting Started</h2>
<p>The first step into multi-threading in PHP is making sure your build is compiled with the <em>&#8211;enable-pcntl </em>flag set.  If that&#8217;s not set, you&#8217;re dead in the water.  Otherwise, we can take a look at a simple example.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$processID</span> <span style="color: #339933;">=</span> pcntl_fork<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$processID</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;I'm in the parent process!&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;I'm in the child process!&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Now, a quick explanation.  The <em><a href="http://www.php.net/manual/en/function.pcntl-fork.php">pcntl_fork()</a> </em>function takes the current running process and makes a copy of it.  Everything (for practical purposes) is copied into this new child process except the process id(pid) which is changed to something new.  This is where things get a bit weird.  When <a href="http://www.php.net/manual/en/function.pcntl-fork.php"><em>pcntl_fork()</em></a> executes, the pid of the child process is returned to the parents thread of execution.  A value of 0(zero) is returned to the child process&#8217; thread of execution.  Since you can differentiate between threads of execution, you can make them do different things with a simple if statement like above.  So what does this program print?</p>
<pre>
I'm in the parent process!
I'm in the child process!
</pre>
<p>or</p>
<pre>
I'm in the child process!
I'm in the parent process!
</pre>
<p>It can actually go either way here.  It depends entirely on how your operating system decided to schedule the processes.  But remember, the child process is an <span style="text-decoration: underline;">exact</span> (not entirely true, but let&#8217;s go with it) copy of the parent process.  So what happens if we change the code a bit.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$processID</span> <span style="color: #339933;">=</span> pcntl_fork<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$processID</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;I'm in the parent process!&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;I'm in the child process!&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;End of the line folks.&quot;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Since the last <em>echo</em> statement exists in both parent and child processes, you&#8217;ll get:</p>
<pre>
I'm in the parent process!
End of the line folks.
I'm in the child process!
End of the line folks.
</pre>
<p></p>
<h2>Waiting for the Child</h2>
<p>One of the problems that you run in to with writing multi-threaded programs is that the child process can finish before the parent, or the parent can finish before the child.  You just never really know.  So you need a way to wait for processes to finish.  Lucky for us, PHP at least provides this functionality for us.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$pid</span><span style="color: #339933;">=</span>pcntl_fork<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$pid</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     pctnl_waitpid<span style="color: #009900;">&#40;</span><span style="color: #000088;">$pid</span><span style="color: #339933;">,</span><span style="color: #000088;">$status</span><span style="color: #339933;">,</span>WUNTRACED<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;In parent process!&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;In child process!&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>By using the <a href="http://www.php.net/manual/en/function.pcntl-waitpid.php"><em>pcntl_waitpid()</em></a> function, we can force the parent process to wait for the child process to finish executing.  This is handy for if you have a critical procedure that your child process must complete before the parent can continue.  In our case, the output will always be:</p>
<pre>
In child process!
In parent process!
</pre>
<h2>Next Time&#8230;</h2>
<p><span style="text-decoration: line-through;">That&#8217;s all for now, but soon I&#8217;ll have</span> <a href="http://www.re-cycledair.com/php-dark-arts-multi-processing-part-2">The 2nd (and last) part of this article up for your enjoyment</a>.  In that part, we&#8217;ll cover some more advanced notions like getting/setting priority, setting alarms, and signal processing.   You should <a href="http://www.twitter.com/recycledairwp">follow me on Twitter</a> and/or become a fan on <strong>Facebook</strong> to find out when this exciting(?) article comes out.</p>
 <img src="http://www.re-cycledair.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=752" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.re-cycledair.com/php-dark-arts-multi-threading-part-1/feed</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced
Database Caching 2/41 queries in 0.824 seconds using disk: basic
Object Caching 655/746 objects using disk: basic

Served from: www.re-cycledair.com @ 2012-02-07 23:26:16 -->
