<?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>Bryan Garber's Blog &#187; Programação</title>
	<atom:link href="http://bgarber.notapipe.org/blog/category/programacao/feed/" rel="self" type="application/rss+xml" />
	<link>http://bgarber.notapipe.org/blog</link>
	<description>Where nerds collide!</description>
	<lastBuildDate>Mon, 12 Dec 2011 16:46:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Hacking /proc &#8211; tempo de execução de um processo em C</title>
		<link>http://bgarber.notapipe.org/blog/2011/05/hacking-proc-tempo-de-execucao-de-um-processo-em-c/</link>
		<comments>http://bgarber.notapipe.org/blog/2011/05/hacking-proc-tempo-de-execucao-de-um-processo-em-c/#comments</comments>
		<pubDate>Mon, 23 May 2011 19:49:09 +0000</pubDate>
		<dc:creator>Bryan</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Nerd]]></category>
		<category><![CDATA[Programação]]></category>

		<guid isPermaLink="false">http://bgarber.notapipe.org/blog/?p=286</guid>
		<description><![CDATA[Recentemente precisei descobrir, usando C, o tempo de execução de um processo. Ao invés de tentar um simples system(&#8220;ps aux &#124; grep &#60;pid&#62;&#8221;), pensei em utilizar algo mais esperto: a árvore montada no /proc. O /proc mantém em sua estrutura de diretórios arquivos para cada processo sendo executado na máquina, tendo um diretório específico para [...]]]></description>
			<content:encoded><![CDATA[<p>Recentemente precisei descobrir, usando C, o tempo de execução de um processo. Ao invés de tentar um simples <em>system(&#8220;ps aux | grep &lt;pid&gt;&#8221;)</em>, pensei em utilizar algo mais esperto: a árvore montada no <em>/proc</em>. O <em>/proc</em> mantém em sua estrutura de diretórios arquivos para cada processo sendo executado na máquina, tendo um diretório específico para cada PID. Bom, não vou entrar em detalhes sobre como está organizado o <em>/proc</em> neste post, mas podemos encontrar uma boa referência <a title="The /proc filesystem" href="http://www.comptechdoc.org/os/linux/howlinuxworks/linux_hlproc.html" target="_blank">aqui</a>.</p>
<p>Como podemos ver na lista de arquivos dentro de <em>/proc/&lt;pid&gt;</em>, o diretório de cada PID possui um arquivo chamado <em>stat</em>. Uma das várias informações guardadas neste arquivo é o <em>starttime</em>. Então a primeira coisa que vamos fazer é abrir o stat do PID desejado no nosso programa:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">char</span> stat_file<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">80</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> pid<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> ac <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">2</span> <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Error: one argument is needed!<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    exit<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
pid <span style="color: #339933;">=</span> atoi<span style="color: #009900;">&#40;</span>av<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
snprintf<span style="color: #009900;">&#40;</span>stat_file<span style="color: #339933;">,</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span>stat_file<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;/proc/%d/stat&quot;</span><span style="color: #339933;">,</span> pid<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
proc_time <span style="color: #339933;">=</span> fopen<span style="color: #009900;">&#40;</span>stat_file<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;r&quot;</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: #339933;">!</span>proc_time <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Some strange error occurred while opening the file!<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    exit<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Com o <em>stat</em> do processo aberto, podemos procurar a 22ª <em>string</em> deste arquivo, que refere-se ao campo <em>starttime</em> do processo.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">freadln<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>line<span style="color: #339933;">,</span> proc_time<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">char</span> <span style="color: #339933;">*</span>jiff_from_boot_str <span style="color: #339933;">=</span> s_token<span style="color: #009900;">&#40;</span>line<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot; &quot;</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">22</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">long</span> <span style="color: #993333;">int</span> jiff_from_boot <span style="color: #339933;">=</span> atoi<span style="color: #009900;">&#40;</span>jiff_from_boot_str<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Onde as funções <em>freadln</em> e <em>s_token</em> são definidas como:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">size_t freadln <span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">**</span>line<span style="color: #339933;">,</span> FILE <span style="color: #339933;">*</span>stream<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">char</span> c<span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> counter <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
    fread<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>c<span style="color: #339933;">,</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">,</span> stream<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: #009900;">&#40;</span>c <span style="color: #339933;">!=</span> <span style="color: #ff0000;">'<span style="color: #000099; font-weight: bold;">\n</span>'</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>feof<span style="color: #009900;">&#40;</span>stream<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        counter <span style="color: #339933;">+=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>line<span style="color: #009900;">&#41;</span> <span style="color: #339933;">=</span> realloc<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>line<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> counter <span style="color: #339933;">*</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>line<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#91;</span>counter <span style="color: #339933;">-</span> <span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> c<span style="color: #339933;">;</span>
&nbsp;
        fread<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>c<span style="color: #339933;">,</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">,</span> stream<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    counter <span style="color: #339933;">+=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>line<span style="color: #009900;">&#41;</span> <span style="color: #339933;">=</span> realloc<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>line<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> counter <span style="color: #339933;">*</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>line<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#91;</span>counter <span style="color: #339933;">-</span> <span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #ff0000;">'<span style="color: #006699; font-weight: bold;">\0</span>'</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> counter <span style="color: #339933;">-</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">char</span><span style="color: #339933;">*</span> s_token <span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span><span style="color: #339933;">*</span> str<span style="color: #339933;">,</span> <span style="color: #993333;">char</span><span style="color: #339933;">*</span> sep<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> i<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>s <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span> strdup<span style="color: #009900;">&#40;</span>str<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>ret <span style="color: #339933;">=</span> strtok<span style="color: #009900;">&#40;</span>s<span style="color: #339933;">,</span> sep<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    i<span style="color: #339933;">--;</span>
    <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">&gt;</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        ret <span style="color: #339933;">=</span> strtok<span style="color: #009900;">&#40;</span>NULL<span style="color: #339933;">,</span> sep<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        i<span style="color: #339933;">--;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>ret<span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">return</span> NULL<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> ret<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>A primeira função serve para ler uma linha de um arquivo (não gosto de <em>sscanf</em> ou <em>fgets</em> <img src='http://bgarber.notapipe.org/blog/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> ) e a outra serve para ler <em>tokens</em> de uma <em>string</em> a partir de um delimitador sem alterar a <em>string</em> original.</p>
<p>Como podemos reparar, o campo <em>starttime</em> no arquivo <em>stat</em> não está em segundos. Está em <em>jiffies</em> (um tipo de <em>tick</em> de relógio do Linux). O valor de <em>jiffies</em> por segundo é configurado na compilação do <em>kernel</em>. Para obter este valor, temos que realizar a seguinte consulta:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">long</span> <span style="color: #993333;">int</span> jiffies_per_sec <span style="color: #339933;">=</span> sysconf<span style="color: #009900;">&#40;</span>_SC_CLK_TCK<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Agora fica fácil descobrir quantos segundos tinha se passado desde o <em>boot</em> até o início do programa. Basta dividirmos jiff_from_boot por jiffies_per_sec! Mas como queremos o tempo de execução do programa, vamos esperar para adicionar na fórmula final. Como pode-se imaginar, iremos calcular o tempo de execução do programa obtendo o tempo em segundos desde o <em>boot</em> do <em>kernel</em> (<em>uptime</em>) e subtrair pelo segundo de início do programa em questão. Para isso, iremos consultar usando a estrutura <em>sysinfo</em>.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">struct</span> sysinfo sys_inf<span style="color: #339933;">;</span>
sysinfo<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>sys_inf<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Pronto. Esta estrutura já possui um campo com o uptime em segundos, então basta resolver a diferença!</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">long</span> <span style="color: #993333;">int</span> proc_rtime <span style="color: #339933;">=</span> sys_inf.<span style="color: #202020;">uptime</span> <span style="color: #339933;">-</span> jiff_from_boot<span style="color: #339933;">/</span>jiffies_per_sec<span style="color: #339933;">;</span>
<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Process %d running time: %ld secs<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> pid<span style="color: #339933;">,</span> proc_rtime<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Bom, acho que é isso. Caso queiram dar uma olhada no meu arquivo C, ele está disponível <a href="http://bgarber.notapipe.org/blog/wp-content/uploads/2011/05/main.c">aqui</a>. Nele poderás ver os <em>includes</em> necessários para compilar o teu código-fonte.</p>
<div style="float: right; margin-left: 10px;"><a href="http://twitter.com/share?url=http://bgarber.notapipe.org/blog/2011/05/hacking-proc-tempo-de-execucao-de-um-processo-em-c/&via=bgarber&text=Hacking /proc - tempo de execução de um processo em C&related=:&lang=en&count=horizontal" class="twitter-share-button">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div>]]></content:encoded>
			<wfw:commentRss>http://bgarber.notapipe.org/blog/2011/05/hacking-proc-tempo-de-execucao-de-um-processo-em-c/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Be careful with that &#8220;unsigned&#8221;!</title>
		<link>http://bgarber.notapipe.org/blog/2011/01/be-careful-with-that-unsigned/</link>
		<comments>http://bgarber.notapipe.org/blog/2011/01/be-careful-with-that-unsigned/#comments</comments>
		<pubDate>Mon, 17 Jan 2011 16:01:41 +0000</pubDate>
		<dc:creator>Bryan</dc:creator>
				<category><![CDATA[english]]></category>
		<category><![CDATA[Programação]]></category>

		<guid isPermaLink="false">http://bgarber.notapipe.org/blog/?p=202</guid>
		<description><![CDATA[On a day-to-day routine of programming in C, it&#8217;s a common practice declare a special type for &#8220;unsigned int&#8221; (or even creating macros). The following lines show some of this practice: #define U32 unsigned int #define UINT32 unsigned int &#160; typedef unsigned int UINT32 Remember that these all declarations are &#8220;unsigned&#8221;. I comment this because [...]]]></description>
			<content:encoded><![CDATA[<p>On a day-to-day routine of programming in C, it&#8217;s a common practice declare a special type for &#8220;unsigned int&#8221; (or even creating macros). The following lines show some of this practice:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#define U32    unsigned int</span>
<span style="color: #339933;">#define UINT32 unsigned int</span>
&nbsp;
<span style="color: #993333;">typedef</span> <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> UINT32</pre></div></div>

<p>Remember that these all declarations are &#8220;unsigned&#8221;. I comment this because I&#8217;ve already seen codes such like:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">typedef</span> <span style="color: #993333;">struct</span> _foobar <span style="color: #009900;">&#123;</span>
    UINT32 u32_field<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> foobar<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// code goes on...</span>
...
&nbsp;
<span style="color: #202020;">foobar</span> <span style="color: #339933;">*</span>some_struct_ptr<span style="color: #339933;">;</span>
some_struct_ptr <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>foobar <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span> malloc<span style="color: #009900;">&#40;</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span>foobar<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// more code...</span>
...
<span style="color: #202020;">ASSERT</span><span style="color: #009900;">&#40;</span>some_struct_ptr<span style="color: #339933;">-&gt;</span>u32_field <span style="color: #339933;">&gt;=</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>What&#8217;s wrong here? The ASSERT call is always true! So this is an unnecessary test! This does not affect the code execution at all, but in greater projects, where the CPU cicles are so precious as diamonds, or if you want to deliver a code that is clean of warnings while building your source, you will need to remove these kind of calls.</p>
<div style="float: right; margin-left: 10px;"><a href="http://twitter.com/share?url=http://bgarber.notapipe.org/blog/2011/01/be-careful-with-that-unsigned/&via=bgarber&text=Be careful with that "unsigned"!&related=:&lang=en&count=horizontal" class="twitter-share-button">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div>]]></content:encoded>
			<wfw:commentRss>http://bgarber.notapipe.org/blog/2011/01/be-careful-with-that-unsigned/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dark Sorcering in C: utilizando bit-fields</title>
		<link>http://bgarber.notapipe.org/blog/2009/07/dark-sorcering-in-c-utilizando-bit-fields/</link>
		<comments>http://bgarber.notapipe.org/blog/2009/07/dark-sorcering-in-c-utilizando-bit-fields/#comments</comments>
		<pubDate>Thu, 30 Jul 2009 13:10:40 +0000</pubDate>
		<dc:creator>Bryan</dc:creator>
				<category><![CDATA[Programação]]></category>

		<guid isPermaLink="false">http://bgarber.notapipe.org/blog/?p=79</guid>
		<description><![CDATA[Mais um post programador-geek-útil: bit-fields. Para quem não conhece, em C pode-se criar coisas &#8220;bizarras&#8221; do tipo estruturas com campos de tamanho 1, 2 ou n bits. Sim, eu não me enganei. É isso mesmo o que tu entendeu. Em C podemos criar estruturas com campos de apenas 1 bit, por exemplo. Aliás, por sinal, [...]]]></description>
			<content:encoded><![CDATA[<p>Mais um post programador-geek-útil: bit-fields. Para quem não conhece, em C pode-se criar coisas &#8220;bizarras&#8221; do tipo estruturas com campos de tamanho 1, 2 ou n <em>bits</em>. Sim, eu não me enganei. É isso mesmo o que tu entendeu. Em C podemos criar estruturas com campos de apenas 1 bit, por exemplo. Aliás, por sinal, tu pode até mesmo criar uma estrutura com apenas 1 bit.</p>
<p>&#8220;Mas como isso?&#8221; tu te pergunta. É mais fácil do que parece. Basta declarar a estrutura e, para cada campo, dizer quantos bits tu quer. Simples assim:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">struct</span> byte_t <span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> high<span style="color: #339933;">:</span> <span style="color: #0000dd;">4</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> low<span style="color: #339933;">:</span>  <span style="color: #0000dd;">4</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Neste caso, estamos declarando uma estrutura com dois campos, cada um com 4 bits. Viram como é simples? Neste caso, nossa estrutura terá o tamanho de 8 <em>bits</em>, 1 <em>byte</em> no final das contas. Mas nada me impede de declará-la assim:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">struct</span> bit_t <span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> val<span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Agora temos uma estrutura de apenas 1 <em>bit</em> de tamanho! Faça o teste: tente colocar algo mais do que 0 ou 1 no campo val da estrutura para ver se o GCC não reclama com um <em>warning</em>!</p>
<p>Algo que preciso lembrar é que o comando <em>sizeof()</em> não irá funcionar para a estrutura <em>bit_t</em>. Porque? Ora, é óbvio. A função <em>sizeof()</em> retorna seus valores em <em>bytes</em> e não em <em>bits</em>. Já para a estrutura <em>byte_t</em>, nós conseguimos executar o <em>sizeof()</em>, já que seu tamanho é de exatamente 1 <em>byte</em>.</p>
<p><strong>Update</strong>: como comentado pelo meu amigo Fabio Utzig, o tamanho das estruturas em si serão arredondadas para a representação. Por exemplo, caso eu adicione mais um campo na estrutura <em>byte_t</em>, mesmo que seja de um <em>bit</em> apenas, o tamanho total da estrutura será 2 bytes, pois ele arredonda o tamanho. Os campos em si que sempre terão o tamanho em <em>bits</em> especificado.</p>
<div style="float: right; margin-left: 10px;"><a href="http://twitter.com/share?url=http://bgarber.notapipe.org/blog/2009/07/dark-sorcering-in-c-utilizando-bit-fields/&via=bgarber&text=Dark Sorcering in C: utilizando bit-fields&related=:&lang=en&count=horizontal" class="twitter-share-button">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div>]]></content:encoded>
			<wfw:commentRss>http://bgarber.notapipe.org/blog/2009/07/dark-sorcering-in-c-utilizando-bit-fields/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Minix 3 Adventures: fazendo funcionar a rede no VirtualBox</title>
		<link>http://bgarber.notapipe.org/blog/2009/05/minix-3-adventures-fazendo-funcionar-a-rede-no-virtualbox/</link>
		<comments>http://bgarber.notapipe.org/blog/2009/05/minix-3-adventures-fazendo-funcionar-a-rede-no-virtualbox/#comments</comments>
		<pubDate>Sun, 31 May 2009 20:48:49 +0000</pubDate>
		<dc:creator>Bryan</dc:creator>
				<category><![CDATA[Programação]]></category>
		<category><![CDATA[Sistemas Operacionais]]></category>

		<guid isPermaLink="false">http://bgarber.notapipe.org/blog/?p=67</guid>
		<description><![CDATA[Neste semestre, estou fazendo a cadeira de Projeto de Sistemas Operacionais na faculdade. Por opção, resolvi (em conjunto com alguns colegas) usar o Minix 3 como sistema operacional de estudos. Instalei ele, feliz da vida, numa máquina virtual do VirtualBox. O problema é que a rede não queria de jeito nenhum funcionar! A princípio deveria [...]]]></description>
			<content:encoded><![CDATA[<p>Neste semestre, estou fazendo a cadeira de Projeto de Sistemas Operacionais na faculdade. Por opção, resolvi (em conjunto com alguns colegas) usar o Minix 3 como sistema operacional de estudos. Instalei ele, feliz da vida, numa máquina virtual do VirtualBox. O problema é que a rede não queria de jeito nenhum funcionar! A princípio deveria funcionar, escolhi o driver certo na instalação (AMD Lance, emulado pelo VMWare e pelo VirrtualBox), mas não funcionava. Depois de muito pesquisar, consegui fazer funcionar. Aqui vão as dicas!</p>
<p>Depois de completada a instalação do Minix 3, reinicie o sistema (não esqueça de botar no VirtualBox para ele não montar o cdrom do Minix3) e execute primeiramente estes passos:</p>
<ol>
<li>Com o sistema reiniciado, coloque a imagem do CD do Minix 3 de volta.</li>
<li>Como root, execute &#8220;packman&#8221;.</li>
<li>Procura o número do vim, para instalá-lo do CD&#8230; ;-P</li>
<li>Cuidado para não deixar ele tentar atualizar a lista de arquivos da internet (o que tu não tem ainda&#8230; hehehehe&#8230;)</li>
</ol>
<p>Estes foram somente os passos para instalar o vim&#8230; hehehehe&#8230; Os passos que segui para fazer a rede funcionar no Minix 3 foram estes:</p>
<ol>
<li>Edite o arquivo &#8220;/usr/etc/rc&#8221; (com o vim).</li>
<li> Vá para a linha 82; ela diz &#8220;Starting services:&#8221;.  Vá para a  próxima linha;  ela começa com &#8220;up random&#8221;.</li>
<li> Aperte &#8220;v&#8221; (para entrar em modo visual) e vá selecionando até o primeiro &#8220;fi&#8221; que tu encontrar.</li>
<li> Recorte estas linhas.</li>
<li> Agora, vá até a linha que diz &#8220;up inet&#8221;.</li>
<li> Cole as linhas que tu copiaste logo em cima desta linha.</li>
<li> Vá para baixo, até onde diz &#8220;intr -t 20 hostaddr -h&#8221; (use o &#8220;/&#8221; do vim).</li>
<li>Mude o &#8220;20&#8243; para &#8220;30&#8243;</li>
</ol>
<p>Esta é a primeira parte da solução&#8230; hehehehe&#8230; Agora vamos para o kernel&#8230;</p>
<ol>
<li>Dá um cd /usr/src/drivers/lance</li>
<li> vim lance.c</li>
<li> A partir da linha 632, edite da forma como segue.</li>
<li>Comente as seguintes linhas:</li>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>ec<span style="color: #339933;">-&gt;</span>ec_linmem <span style="color: #339933;">!=</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    assert<span style="color: #009900;">&#40;</span> <span style="color: #0000dd;">0</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #808080; font-style: italic;">/*phys2seg(&amp;ec-&gt;ec_memseg, &amp;ec-&gt;ec_memoff, ec-&gt;ec_linmem);*/</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/* XXX */</span> <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>ec<span style="color: #339933;">-&gt;</span>ec_linmem <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span> ec<span style="color: #339933;">-&gt;</span>ec_linmem<span style="color: #339933;">=</span> <span style="color: #208080;">0xFFFF0000</span><span style="color: #339933;">;</span></pre></div></div>

<li>E adicione a seguinte linha:</li>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">ec<span style="color: #339933;">-&gt;</span>ec_linmem<span style="color: #339933;">=</span> <span style="color: #208080;">0xFFFF0000</span><span style="color: #339933;">;</span></pre></div></div>

<li>Salve o arquivo e saia do vim.</li>
<li>Vá até a pasta /usr/src/ e execute o seguinte comando:</li>
<p>	<strong># make world</strong></li>
<li>Vai demorar uns 15 ou 20 minutos, aproveite para tomar um cafézinho&#8230;</li>
<li>Reinicie o Minix 3 (não esqueça de desmontar a imagem do cdrom do VirtualBox&#8230;).</li>
<li>Depois de reiniciado, dê um ps ax | grep lance.</li>
<li>Com o PID do driver de rede (provavelmente, será 55), nós vamos nos aproveitar do Reincarnation Server do Minix 3 e matar o processo do driver de rede. Sim, isso mesmo:</li>
<p>	<strong># kill -9 55</strong></p>
<li>O RS vai verificar a morte do processo driver e reiniciá-lo, agora sim a rede vai estar funcionando 100%.</li>
</ol>
<p>O único problema é que toda a vez que reiniciarmos o sistema teremos que executar o comando kill. Mas, por mim, tá tudo bem. <img src='http://bgarber.notapipe.org/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<div style="float: right; margin-left: 10px;"><a href="http://twitter.com/share?url=http://bgarber.notapipe.org/blog/2009/05/minix-3-adventures-fazendo-funcionar-a-rede-no-virtualbox/&via=bgarber&text=Minix 3 Adventures: fazendo funcionar a rede no VirtualBox&related=:&lang=en&count=horizontal" class="twitter-share-button">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div>]]></content:encoded>
			<wfw:commentRss>http://bgarber.notapipe.org/blog/2009/05/minix-3-adventures-fazendo-funcionar-a-rede-no-virtualbox/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Decepções com o Eclipse</title>
		<link>http://bgarber.notapipe.org/blog/2007/04/decepcoes-com-o-eclipse/</link>
		<comments>http://bgarber.notapipe.org/blog/2007/04/decepcoes-com-o-eclipse/#comments</comments>
		<pubDate>Wed, 11 Apr 2007 17:56:36 +0000</pubDate>
		<dc:creator>Bryan</dc:creator>
				<category><![CDATA[Programação]]></category>

		<guid isPermaLink="false">http://bgarber.wordpress.com/2007/04/11/decepcoes-com-o-eclipse/</guid>
		<description><![CDATA[Últimamente tenho trabalhado junto ao projeto de pesquisa sobre redes BitTorrent. Neste projeto, utilizamos a Java como linguagem. A maioria dos participantes usa o Eclipse como interface para programar. Pois bem, tentei usar o tal do Eclipse uma vez que fosse. De início gostei da interface e eu teria alguns vários pontos positivos para citar [...]]]></description>
			<content:encoded><![CDATA[<p>Últimamente tenho trabalhado junto ao projeto de pesquisa sobre redes BitTorrent. Neste projeto, utilizamos a Java como linguagem. A maioria dos participantes usa o Eclipse como interface para programar. Pois bem, tentei usar o tal do Eclipse uma vez que fosse. De início gostei da interface e eu teria alguns vários pontos positivos para citar sobre a interface, mas uma coisa me fez ficar de cabelo em pé: o Eclipse não compilava meu projeto. Acusa erros em vários pontos do código, onde não existiam antes.</p>
<p>Agora, qualquer pessoa me diria &#8220;tu deve estar fazendo algo errado&#8221;. Não. Não estou. Entro na linha de comandos do Linux e mando compilar os .java: compila. Acusa alguns warnings, mas compila. E funciona!</p>
<p>Realmente, não entendo o Eclipse. Já arrumei um monte de coisa e nada o faz funcionar. Desisti e estou agora utilizando o gedit mesmo. E, verdade, é muito melhor do que o Eclipse&#8230;</p>
<div style="float: right; margin-left: 10px;"><a href="http://twitter.com/share?url=http://bgarber.notapipe.org/blog/2007/04/decepcoes-com-o-eclipse/&via=bgarber&text=Decepções com o Eclipse&related=:&lang=en&count=horizontal" class="twitter-share-button">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div>]]></content:encoded>
			<wfw:commentRss>http://bgarber.notapipe.org/blog/2007/04/decepcoes-com-o-eclipse/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

