<?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>High Fibre Programming &#187; thread</title>
	<atom:link href="http://www.4pmp.com/tag/thread/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.4pmp.com</link>
	<description>PHP, MySQL, C, Java, Linux and other great after dinner speech topics</description>
	<lastBuildDate>Tue, 17 Jan 2012 09:10:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.5</generator>
		<item>
		<title>cast from pointer to integer of different size &#8211; cast to pointer from integer of different size</title>
		<link>http://www.4pmp.com/2010/10/cast-from-pointer-to-integer-of-different-size-cast-to-pointer-from-integer-of-different-size/</link>
		<comments>http://www.4pmp.com/2010/10/cast-from-pointer-to-integer-of-different-size-cast-to-pointer-from-integer-of-different-size/#comments</comments>
		<pubDate>Fri, 08 Oct 2010 12:48:45 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[C]]></category>
		<category><![CDATA[cast]]></category>
		<category><![CDATA[casting]]></category>
		<category><![CDATA[pointers]]></category>
		<category><![CDATA[pthread]]></category>
		<category><![CDATA[thread]]></category>
		<category><![CDATA[void]]></category>

		<guid isPermaLink="false">http://www.4pmp.com/?p=322</guid>
		<description><![CDATA[On a 32-bit system my code compiled without any problem. On a 64-bit system I get the warnings: warning: cast from pointer to integer of different size warning: cast to pointer from integer of different size It turned out the problem was how I was passing an integer to a new thread using pthread_create(). The [...]]]></description>
			<content:encoded><![CDATA[<p>On a 32-bit system my code compiled without any problem.   On a 64-bit system I get the warnings:</p>
<blockquote><p>warning: cast from pointer to integer of different size<br />
warning: cast to pointer from integer of different size</p></blockquote>
<p>It turned out the problem was how I was passing an integer to a new thread using pthread_create().   The final argument is a void pointer which can be used to pass a pointer to some data.   In my case I was casting an integer to a void pointer in the parent thread, and then re-casting it back to an integer inside the thread.</p>
<p>On a 32-bit system both void pointers and integers occupy 32 bits so everything was ok.   On my 64-bit system, integers are still 32-bits but void pointers are 64-bits.</p>
<p>One solution use long instead of int, which are, according to the C99 standard, the same size as void pointers on 32-bit and 64-bit systems.</p>
<p>The proper solution is not to cast integers to pointers in the first place but use pointers throughout:</p>
<pre class="brush: cpp;">
    void hello(void *i)
    {
        int *pointer;

        /* Cast the void pointer to a integer pointer */
        pointer = (int *) i;

        /* Display the value pointed to by the pointer */
        printf(&quot;Value is: %d\n&quot;, *pointer);
    }

    int main()
    {
        int value, *pointer;

        /* Assign a value */
        value = 11;

        /* Display the original value */
        printf(&quot;Value is: %d\n&quot;, value);

        /* Set the pointer to the location of the value */
        *pointer = value;

        /* Call a function, cast the pointer to a void pointer */
        hello((void *)pointer);

        return 1;
    }
</pre>
<p>Of course it should be taken into account that when using threads there is the problem that the value referenced by the pointer could be changed by any of the threads.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.4pmp.com/2010/10/cast-from-pointer-to-integer-of-different-size-cast-to-pointer-from-integer-of-different-size/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spinning command line cursor in Java</title>
		<link>http://www.4pmp.com/2010/01/spinning-command-line-cursor-in-java/</link>
		<comments>http://www.4pmp.com/2010/01/spinning-command-line-cursor-in-java/#comments</comments>
		<pubDate>Fri, 29 Jan 2010 12:48:31 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[activity]]></category>
		<category><![CDATA[ctrl+c]]></category>
		<category><![CDATA[cursor]]></category>
		<category><![CDATA[indicator]]></category>
		<category><![CDATA[interrupt]]></category>
		<category><![CDATA[multithreaded]]></category>
		<category><![CDATA[spin]]></category>
		<category><![CDATA[spinning]]></category>
		<category><![CDATA[thread]]></category>

		<guid isPermaLink="false">http://www.4pmp.com/?p=238</guid>
		<description><![CDATA[As a follow-up to my previous article on displaying a spinning cursor to display program activity, I have created a more useful example that could be adapted for use. The original problem was this &#8211; I was writing a program that performed a particular task and I needed some way of showing the program was [...]]]></description>
			<content:encoded><![CDATA[<p>As a follow-up to my<a href="http://www.4pmp.com/2010/01/spinning-command-line-cursor-in-java-and-php/"> previous article</a> on displaying a spinning cursor to display program activity, I have created a more useful example that could be adapted for use.</p>
<p>The original problem was this &#8211; I was writing a program that performed a particular task and I needed some way of showing the program was alive and functioning correctly whilst doing the task.</p>
<p>In Windows this is done by changing the mouse cursor into an hourglass, unfortunately on the command line we don&#8217;t have such GUI luxuries.   One classic option is to create a spinning line by displaying | / &#8211; \ and so on.</p>
<p>The example below creates two child threads; one to do a particular job (in this case slowly count to 10) and another thread to display a spinning cursor.</p>
<pre class="brush: java;">
/**
 * Spinning cursor test class
 *
 * @author Nick Giles
 */
public class SpinTest
{
    /**
     * Thread which does the stuff we're interested in
     *
     */
    private Thread stuff;

    /**
     * Thread class which does stuff in the background
     *
     */
    private class Stuff implements Runnable
    {
        public void run()
        {
            int result = 0;

            try
            {
                // Slowly count to 10, although you can of course put whatever
                // you want here, presumably something a bit more useful
                while (result &lt; 10)
                {
                    result++;
                    Thread.sleep(1000);
                }
            }
            catch (InterruptedException e)
            {
                // If interrupted then quietly end the thread, you may well
                // want to handle this in some way
            }
        }
    }

    /**
     * Spinner thread
     *
     */
    private class Spinner implements Runnable
    {
        public void run()
        {
            String[] phases = {&quot;|&quot;, &quot;/&quot;, &quot;-&quot;, &quot;\\&quot;};

            try
            {
                while (true)
                {
                    for (String phase : phases)
                    {
                        System.out.printf(&quot;\b&quot;+phase);

                        Thread.sleep(100);
                    }
                }
            }
            catch (InterruptedException e)
            {
                // No need to do anything if interrupted
            }
        }
    }

    /**
     * Handles all shutdown functions
     *
     */
    public class ShutdownHandler extends Thread
    {
        public void run()
        {
            // On interrupt, stop doing stuff
            stuff.interrupt();
        }
    }

    public void doStuff()
    {
        try
        {
            // Attach an object to handle shutdown signals (i.e. ctrl+c)
            Runtime.getRuntime().addShutdownHook(new ShutdownHandler()); 

            // Create a new thread for spinning the cursor
            Thread spinner = new Thread(new Spinner());

            // Create a new thread for doing stuff
            this.stuff = new Thread(new Stuff());

            // Nice message to user
            System.out.printf(&quot;Doing stuff...  &quot;);

            // Start doing stuff
            this.stuff.start();

            // Start spinning the cursor
            spinner.start();

            // Check the thread doing stuff is still doing stuff
            while (stuff.isAlive())
            {
                stuff.join(1000);
            }

            System.out.printf(&quot;\bDone.\n&quot;);

            // The thread doing stuff has finished, so stop spinning
            spinner.interrupt();

            // Wait for the spinning thread to terminate
            spinner.join();

            System.out.println(&quot;The End.&quot;);
        }
        catch (InterruptedException e)
        {
            System.out.println(&quot;Interrupted&quot;);
        }
    }

    /**
     * Main method
     *
     */
    public static void main(String[] args)
    {
        SpinTest test = new SpinTest();

        test.doStuff();
    }
}
</pre>
<p>It&#8217;s a fairly basic implementation but it should be fairly simple to extend it for a real-world application.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.4pmp.com/2010/01/spinning-command-line-cursor-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Simple Daemon in C</title>
		<link>http://www.4pmp.com/2009/12/a-simple-daemon-in-c/</link>
		<comments>http://www.4pmp.com/2009/12/a-simple-daemon-in-c/#comments</comments>
		<pubDate>Thu, 10 Dec 2009 08:33:54 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[C]]></category>
		<category><![CDATA[daemon]]></category>
		<category><![CDATA[fork]]></category>
		<category><![CDATA[periodically]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[process]]></category>
		<category><![CDATA[signal handler]]></category>
		<category><![CDATA[signals]]></category>
		<category><![CDATA[thread]]></category>

		<guid isPermaLink="false">http://www.4pmp.com/?p=209</guid>
		<description><![CDATA[A daemon is a process which runs in the background of your computer, periodically carrying out a specific task. The following is an example of a simple daemon written in C. It works by forking to create a child process, the parent then terminates but the child carries on in the background &#8211; entering a [...]]]></description>
			<content:encoded><![CDATA[<p>A daemon is a process which runs in the background of your computer, periodically carrying out a specific task.   The following is an example of a simple daemon written in C.   It works by forking to create a child process, the parent then terminates but the child carries on in the background &#8211; entering a continuous loop of doing a task and then sleeping.   The child process is of course an identical copy of the parent so care must be taken to close all file descriptors, thus detaching the child completely from the calling process.   The deamonised process is controlled by sending it signals which it can catch and take action accordingly.   In the example below, the process is terminated by sending SIGINT or SIGTERM, but you can of course add in your own handling &#8211; for example to re-read config data on SIGHUP.</p>
<pre class="brush: cpp;">
#include &lt;stdio.h&gt;
#include &lt;signal.h&gt;
#include &lt;syslog.h&gt;
#include &lt;errno.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;fcntl.h&gt;
#include &lt;unistd.h&gt;
#include &lt;string.h&gt;

#define DAEMON_NAME &quot;simpledaemon&quot;

    void daemonShutdown();
    void signal_handler(int sig);
    void daemonize(char *rundir, char *pidfile);

    int pidFilehandle;

    void signal_handler(int sig)
    {
        switch(sig)
        {
            case SIGHUP:
                syslog(LOG_WARNING, &quot;Received SIGHUP signal.&quot;);
                break;
            case SIGINT:
            case SIGTERM:
                syslog(LOG_INFO, &quot;Daemon exiting&quot;);
                daemonShutdown();
                exit(EXIT_SUCCESS);
                break;
            default:
                syslog(LOG_WARNING, &quot;Unhandled signal %s&quot;, strsignal(sig));
                break;
        }
    }

    void daemonShutdown()
    {
        close(pidFilehandle);
    }

    void daemonize(char *rundir, char *pidfile)
    {
        int pid, sid, i;
        char str[10];
        struct sigaction newSigAction;
        sigset_t newSigSet;

        /* Check if parent process id is set */
        if (getppid() == 1)
        {
            /* PPID exists, therefore we are already a daemon */
            return;
        }

        /* Set signal mask - signals we want to block */
        sigemptyset(&amp;newSigSet);
        sigaddset(&amp;newSigSet, SIGCHLD);  /* ignore child - i.e. we don't need to wait for it */
        sigaddset(&amp;newSigSet, SIGTSTP);  /* ignore Tty stop signals */
        sigaddset(&amp;newSigSet, SIGTTOU);  /* ignore Tty background writes */
        sigaddset(&amp;newSigSet, SIGTTIN);  /* ignore Tty background reads */
        sigprocmask(SIG_BLOCK, &amp;newSigSet, NULL);   /* Block the above specified signals */

        /* Set up a signal handler */
        newSigAction.sa_handler = signal_handler;
        sigemptyset(&amp;newSigAction.sa_mask);
        newSigAction.sa_flags = 0;

            /* Signals to handle */
            sigaction(SIGHUP, &amp;newSigAction, NULL);     /* catch hangup signal */
            sigaction(SIGTERM, &amp;newSigAction, NULL);    /* catch term signal */
            sigaction(SIGINT, &amp;newSigAction, NULL);     /* catch interrupt signal */

        /* Fork*/
        pid = fork();

        if (pid &lt; 0)
        {
            /* Could not fork */
            exit(EXIT_FAILURE);
        }

        if (pid &gt; 0)
        {
            /* Child created ok, so exit parent process */
            printf(&quot;Child process created: %d\n&quot;, pid);
            exit(EXIT_SUCCESS);
        }

        /* Child continues */

        umask(027); /* Set file permissions 750 */

        /* Get a new process group */
        sid = setsid();

        if (sid &lt; 0)
        {
            exit(EXIT_FAILURE);
        }

        /* close all descriptors */
        for (i = getdtablesize(); i &gt;= 0; --i)
        {
            close(i);
        }

        /* Route I/O connections */
        close(STDIN_FILENO);
        close(STDOUT_FILENO);
        close(STDERR_FILENO);

        chdir(rundir); /* change running directory */

        /* Ensure only one copy */
        pidFilehandle = open(pidfile, O_RDWR|O_CREAT, 0600);

        if (pidFilehandle == -1 )
        {
            /* Couldn't open lock file */
            syslog(LOG_INFO, &quot;Could not open PID lock file %s, exiting&quot;, pidfile);
            exit(EXIT_FAILURE);
        }

        /* Try to lock file */
        if (lockf(pidFilehandle,F_TLOCK,0) == -1)
        {
            /* Couldn't get lock on lock file */
            syslog(LOG_INFO, &quot;Could not lock PID lock file %s, exiting&quot;, pidfile);
            exit(EXIT_FAILURE);
        }

        /* Get and format PID */
        sprintf(str,&quot;%d\n&quot;,getpid());

        /* write pid to lockfile */
        write(pidFilehandle, str, strlen(str));
    }

    int main()
    {
        /* Debug logging
        setlogmask(LOG_UPTO(LOG_DEBUG));
        openlog(DAEMON_NAME, LOG_CONS, LOG_USER);
        */

        /* Logging */
        setlogmask(LOG_UPTO(LOG_INFO));
        openlog(DAEMON_NAME, LOG_CONS | LOG_PERROR, LOG_USER);

        syslog(LOG_INFO, &quot;Daemon starting up&quot;);

        /* Deamonize */
        daemonize(&quot;/tmp/&quot;, &quot;/tmp/daemon.pid&quot;);

        syslog(LOG_INFO, &quot;Daemon running&quot;);

        while (1)
        {
            syslog(LOG_INFO, &quot;daemon says hello&quot;);

            sleep(1);
        }
    }
</pre>
<p>The above example is only simple but it serves as a good starting point to create your own daemon.   In my next article I will demonstrate how it can be extended to periodically call a PHP script.</p>
<p>If I find enough time I will also demonstrate how it can be extended from being a single-threaded daemon to a multi-threaded daemon, maintaining a continuous pool of x threads, each doing a given task.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.4pmp.com/2009/12/a-simple-daemon-in-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

