<?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>EmbLogic &#187; gkarya1990</title>
	<atom:link href="https://www.emblogic.com/blog/author/gkarya1990/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.emblogic.com/blog</link>
	<description>Embedded System and ARM Training</description>
	<lastBuildDate>Tue, 03 Mar 2020 13:00:06 +0000</lastBuildDate>
	<language>en-US</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.9.1</generator>
	<item>
		<title>UNDERSTANDING FILE PERMISSION</title>
		<link>https://www.emblogic.com/blog/06/understanding-file-permission/</link>
		<comments>https://www.emblogic.com/blog/06/understanding-file-permission/#comments</comments>
		<pubDate>Fri, 06 Jun 2014 04:59:22 +0000</pubDate>
		<dc:creator><![CDATA[gkarya1990]]></dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.emblogic.com/blog/?p=10340</guid>
		<description><![CDATA[Although there are already a lot of good security features built into Linux-based systems, one very important potential vulnerability can exist when local access is granted &#8211; - that is file permission based issues resulting from a user not assigning &#8230; <a href="https://www.emblogic.com/blog/06/understanding-file-permission/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">Although there are already a lot of good security features built into Linux-based systems, one very important potential vulnerability can exist when local access is granted &#8211; - that is file permission based issues resulting from a user not assigning the correct permissions to files and directories. So based upon the need for proper permissions, I will go over the ways to assign permissions and show you some examples where modification may be necessary.</span></span></p>
<p><span style="font-size: 12px"><strong><span style="font-family: arial,helvetica,sans-serif">Basic File Permissions</span></strong></span></p>
<p><strong><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">Permission Groups</span></span></strong></p>
<p><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">Each file and directory has three user based permission groups:</span></span></p>
<ul>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><strong>owner</strong> &#8211; The Owner permissions apply only the owner of the file or directory, they will not impact the actions of other users.</span></span></li>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><strong>group</strong> &#8211; The Group permissions apply only to the group that has been assigned to the file or directory, they will not effect the actions of other users.</span></span></li>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><strong>all users</strong> &#8211; The All Users permissions apply to all other users on the system, this is the permission group that you want to watch the most.</span></span></li>
</ul>
<h2><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">Permission Types</span></span></h2>
<p><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">Each file or directory has three basic permission types:</span></span></p>
<ul>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><strong>read</strong> &#8211; The Read permission refers to a user&#8217;s capability to read the contents of the file.</span></span></li>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><strong>write</strong> &#8211; The Write permissions refer to a user&#8217;s capability to write or modify a file or directory.</span></span></li>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><strong>execute</strong> &#8211; The Execute permission affects a user&#8217;s capability to execute a file or view the contents of a directory.</span></span></li>
</ul>
<h1><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">Viewing the Permissions</span></span></h1>
<p><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">You can view the permissions by checking the file or directory permissions in your favorite GUI File Manager (which I will not cover here) or by reviewing the output of the <em><strong>\&#8221;ls -l\&#8221;</strong></em> command while in the terminal and while working in the directory which contains the file or folder.</p>
<p>The permission in the command line is displayed as: <em><strong>_rwxrwxrwx 1 owner:group</strong></em></span></span></p>
<ol>
<li><span style="font-family: arial,helvetica,sans-serif">User rights/Permissions</span>
<ol>
<li><span style="font-family: arial,helvetica,sans-serif">The first character that I marked with an underscore is the special permission flag that can vary.</span></li>
<li><span style="font-family: arial,helvetica,sans-serif">The following set of three characters (rwx) is for the owner permissions.</span></li>
<li><span style="font-family: arial,helvetica,sans-serif">The second set of three characters (rwx) is for the Group permissions.</span></li>
<li><span style="font-family: arial,helvetica,sans-serif">The third set of three characters (rwx) is for the All Users permissions.</span></li>
</ol>
</li>
<li><span style="font-family: arial,helvetica,sans-serif">Following that grouping since the integer/number displays the number of hardlinks to the file.</span></li>
<li><span style="font-family: arial,helvetica,sans-serif">The last piece is the Owner and Group assignment formatted as Owner:Group.</span></li>
</ol>
<h1><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">Modifying the Permissions</span></span></h1>
<p><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">When in the command line, the permissions are edited by using the command <strong><em>chmod</em></strong>. You can assign the permissions explicitly or by using a binary reference as described below.</span></span></p>
<h2><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">Explicitly Defining Permissions</span></span></h2>
<p><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">To explicity define permissions you will need to reference the Permission Group and Permission Types.</p>
<p>The Permission Groups used are:</span></span></p>
<ul>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><strong>u</strong> &#8211; Owner</span></span></li>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><strong>g</strong> &#8211; Group</span></span></li>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><strong>o</strong> or <strong>a</strong> &#8211; All Users</span></span></li>
</ul>
<p><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">The potential Assignment Operators are + (plus) and &#8211; (minus); these are used to tell the system whether to add or remove the specific permissions.</p>
<p>The Permission Types that are used are:</span></span></p>
<ul>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><strong>r</strong> &#8211; Read</span></span></li>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><strong>w</strong> &#8211; Write</span></span></li>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><strong>x</strong> &#8211; Execute</span></span></li>
</ul>
<p><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">So for an example, lets say I have a file named file1 that currently has the permissions set to <strong>_rw_rw_rw,</strong> which means that the owner, group and all users have read and write permission. Now we want to remove the read and write permissions from the all users group.</p>
<p>To make this modification you would invoke the command: <strong><em>chmod a-rw file1</em></strong><br />
To add the permissions above you would invoke the command: <em><strong>chmod a+rw file1</strong></em></p>
<p>As you can see, if you want to grant those permissions you would change the minus character to a plus to add those permissions. </span></span></p>
<h2><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><em><em>Using Binary References to Set permissions</em></em></span></span></h2>
<p><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">Now that you understand the permissions groups and types this one should feel natural. To set the permission using binary references you must first understand that the input is done by entering three integers/numbers.</p>
<p>A sample permission string would be <strong>chmod 640 file1</strong>, which means that the owner has read and write permissions, the group has read permissions, and all other user have no rights to the file.</p>
<p>The first number represents the Owner permission; the second represents the Group permissions; and the last number represents the permissions for all other users. The numbers are a binary representation of the rwx string. </span></span></p>
<ul>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><em><em><strong>r</strong> = 4</em></em></span></span></li>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><em><em><strong>w</strong> = 2</em></em></span></span></li>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><em><em><strong>x</strong> = 1</em></em></span></span></li>
</ul>
<p><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">You add the numbers to get the integer/number representing the permissions you wish to set. You will need to include the binary permissions for each of the three permission groups.</p>
<p>So to set a file to permissions on file1 to read <strong>_<em>rwxr</em>_____</strong>, you would enter <em><strong>chmod 740 file1</strong></em>. </span></span></p>
<p><strong><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">Owners and Groups</span></span></strong></p>
<p><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">I have made several references to Owners and Groups above, but have not yet told you how to assign or change the Owner and Group assigned to a file or directory.</p>
<p>You use the chown command to change owner and group assignments, the syntax is simple<em><em><em> <strong><em>chown owner:group filename</em></strong><em>, </em></em></em></em>so to change the owner of file1 to user1 and the group to family you would enter <em><em><em><em><strong><em>chown user1:family file1</em></strong><em>. </em></em></em></em></em></span></span></p>
<p><strong><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">Advanced Permissions</span></span></strong></p>
<p><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">The special permissions flag can be marked with any of the following: </span></span></p>
<ul>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><strong>_</strong> &#8211; no special permissions</span></span></li>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><em><strong>d</strong></em> &#8211; directory</span></span></li>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><em><strong>l</strong> </em>- The file or directory is a symbolic link</span></span></li>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><em><strong>s</strong></em> &#8211; This indicated the setuid/setgid permissions. This is not set displayed in the special permission part of the permissions display, but is represented as a <strong>s</strong> in the read portion of the owner or group permissions.</span></span></li>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><em><strong>t</strong></em> &#8211; This indicates the sticky bit permissions. This is not set displayed in the special permission part of the permissions display, but is represented as a <strong>t</strong> in the executable portion of the all users permissions</span></span></li>
</ul>
<p><strong><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">Setuid/Setgid Special Permissions</span></span></strong></p>
<p><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">The setuid/setguid permissions are used to tell the system to run an executable as the owner with the owner\&#8217;s permissions.</p>
<p>Be careful using setuid/setgid bits in permissions. If you incorrectly assign permissions to a file owned by root with the setuid/setgid bit set, then you can open your system to intrusion.</p>
<p>You can only assign the setuid/setgid bit by explicitly defining permissions. The character for the setuid/setguid bit is <strong>s</strong>.</p>
<p>So do set the setuid/setguid bit on file2.sh you would issue the command <em><em><em><em><em><strong><em>chmod g+s file2.sh</em></strong><em>. </em></em></em></em></em></em></span></span></p>
<p><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">Sticky Bit Special Permissions</span></span></p>
<p><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">The sticky bit can be very useful in shared environment because when it has been assigned to the permissions on a directory it sets it so only file owner can rename or delete the said file.</p>
<p>You can only assign the sticky bit by explicitly defining permissions. The character for the sticky bit is <strong>t</strong>.</p>
<p>To set the sticky bit on a directory named dir1 you would issue the command <em><em><em><em><em><em><strong><em>chmod +t dir1</em></strong><em>. </em></em></em></em></em></em></em></span></span></p>
<h1><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><em><em><em><em><em><em><em>When Permissions Are Important</em></em></em></em></em></em></em></span></span></h1>
<p><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">To some users of Mac- or Windows-based computers you don&#8217;t think about permissions, but those environments don&#8217;t focus so aggressively on user based rights on files unless you are in a corporate environment. But now you are running a Linux-based system and permission based security is simplified and can be easily used to restrict access as you please.</p>
<p>So I will show you some documents and folders that you want to focus on and show you how the optimal permissions should be set.<br />
</span></span></p>
<ul>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><em><strong>home directories</strong> </em>- The users\&#8217; home directories are important because you do not want other users to be able to view and modify the files in another user\&#8217;s documents of desktop. To remedy this you will want the directory to have the <strong>drwx______ (700)</strong> permissions, so lets say we want to enforce the correct permissions on the user user1\&#8217;s home directory that can be done by issuing the command <strong>chmod 700 /home/user1</strong>.</span></span></li>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><em><strong>bootloader configuration files</strong> </em>- If you decide to implement password to boot specific operating systems then you will want to remove read and write permissions from the configuration file from all users but root. To do you can change the permissions of the file to 700.</span></span></li>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><em><strong>system and daemon configuration files</strong> </em>- It is very important to restrict rights to system and daemon configuration files to restrict users from editing the contents, it may not be advisable to restrict read permissions, but restricting write permissions is a must. In these cases it may be best to modify the rights to 644.</span></span></li>
<li><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif"><em><strong>firewall scripts</strong></em> &#8211; It may not always be necessary to block all users from reading the firewall file, but it is advisable to restrict the users from writing to the file. In this case the firewall script is run by the root user automatically on boot, so all other users need no rights, so you can assign the 700 permissions.</span></span></li>
</ul>
<p><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">Other examples can be given, but this article is already very lengthy, so if you want to share other examples of needed restrictions please do so in the comments.<em><br />
</em></span></span></p>
<h1><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">Comments Welcome</span></span></h1>
<p><span style="font-size: 11px"><span style="font-family: arial,helvetica,sans-serif">If you have anything to add or want to make a comment or correction please do so in the comments. I look forward to your feedback and wish you the best in your future with Linux-based systems.</span></span></p>
<p>Although there are already a lot of good security features built into Linux-based systems, one very important potential vulnerability can exist when local access is granted &#8211; - that is file permission based issues resulting from a user not assigning the correct permissions to files and directories. So based upon the need for proper permissions, I will go over the ways to assign permissions and show you some examples where modification may be necessary.</p>
<p>Basic File Permissions</p>
<p>Permission Groups</p>
<p>Each file and directory has three user based permission groups:</p>
<p>owner &#8211; The Owner permissions apply only the owner of the file or directory, they will not impact the actions of other users.<br />
group &#8211; The Group permissions apply only to the group that has been assigned to the file or directory, they will not effect the actions of other users.<br />
all users &#8211; The All Users permissions apply to all other users on the system, this is the permission group that you want to watch the most.</p>
<p>Permission Types</p>
<p>Each file or directory has three basic permission types:</p>
<p>read &#8211; The Read permission refers to a user&#8217;s capability to read the contents of the file.<br />
write &#8211; The Write permissions refer to a user&#8217;s capability to write or modify a file or directory.<br />
execute &#8211; The Execute permission affects a user&#8217;s capability to execute a file or view the contents of a directory.</p>
<p>Viewing the Permissions</p>
<p>You can view the permissions by checking the file or directory permissions in your favorite GUI File Manager (which I will not cover here) or by reviewing the output of the \&#8221;ls -l\&#8221; command while in the terminal and while working in the directory which contains the file or folder.</p>
<p>The permission in the command line is displayed as: _rwxrwxrwx 1 owner:group</p>
<p>User rights/Permissions<br />
The first character that I marked with an underscore is the special permission flag that can vary.<br />
The following set of three characters (rwx) is for the owner permissions.<br />
The second set of three characters (rwx) is for the Group permissions.<br />
The third set of three characters (rwx) is for the All Users permissions.<br />
Following that grouping since the integer/number displays the number of hardlinks to the file.<br />
The last piece is the Owner and Group assignment formatted as Owner:Group.</p>
<p>Modifying the Permissions</p>
<p>When in the command line, the permissions are edited by using the command chmod. You can assign the permissions explicitly or by using a binary reference as described below.<br />
Explicitly Defining Permissions</p>
<p>To explicity define permissions you will need to reference the Permission Group and Permission Types.</p>
<p>The Permission Groups used are:</p>
<p>u &#8211; Owner<br />
g &#8211; Group<br />
o or a &#8211; All Users</p>
<p>The potential Assignment Operators are + (plus) and &#8211; (minus); these are used to tell the system whether to add or remove the specific permissions.</p>
<p>The Permission Types that are used are:</p>
<p>r &#8211; Read<br />
w &#8211; Write<br />
x &#8211; Execute</p>
<p>So for an example, lets say I have a file named file1 that currently has the permissions set to _rw_rw_rw, which means that the owner, group and all users have read and write permission. Now we want to remove the read and write permissions from the all users group.</p>
<p>To make this modification you would invoke the command: chmod a-rw file1<br />
To add the permissions above you would invoke the command: chmod a+rw file1</p>
<p>As you can see, if you want to grant those permissions you would change the minus character to a plus to add those permissions.<br />
Using Binary References to Set permissions</p>
<p>Now that you understand the permissions groups and types this one should feel natural. To set the permission using binary references you must first understand that the input is done by entering three integers/numbers.</p>
<p>A sample permission string would be chmod 640 file1, which means that the owner has read and write permissions, the group has read permissions, and all other user have no rights to the file.</p>
<p>The first number represents the Owner permission; the second represents the Group permissions; and the last number represents the permissions for all other users. The numbers are a binary representation of the rwx string.</p>
<p>r = 4<br />
w = 2<br />
x = 1</p>
<p>You add the numbers to get the integer/number representing the permissions you wish to set. You will need to include the binary permissions for each of the three permission groups.</p>
<p>So to set a file to permissions on file1 to read _rwxr_____, you would enter chmod 740 file1.</p>
<p>Owners and Groups</p>
<p>I have made several references to Owners and Groups above, but have not yet told you how to assign or change the Owner and Group assigned to a file or directory.</p>
<p>You use the chown command to change owner and group assignments, the syntax is simple chown owner:group filename, so to change the owner of file1 to user1 and the group to family you would enter chown user1:family file1.</p>
<p>Advanced Permissions</p>
<p>The special permissions flag can be marked with any of the following:</p>
<p>_ &#8211; no special permissions<br />
d &#8211; directory<br />
l &#8211; The file or directory is a symbolic link<br />
s &#8211; This indicated the setuid/setgid permissions. This is not set displayed in the special permission part of the permissions display, but is represented as a s in the read portion of the owner or group permissions.<br />
t &#8211; This indicates the sticky bit permissions. This is not set displayed in the special permission part of the permissions display, but is represented as a t in the executable portion of the all users permissions</p>
<p>Setuid/Setgid Special Permissions</p>
<p>The setuid/setguid permissions are used to tell the system to run an executable as the owner with the owner\&#8217;s permissions.</p>
<p>Be careful using setuid/setgid bits in permissions. If you incorrectly assign permissions to a file owned by root with the setuid/setgid bit set, then you can open your system to intrusion.</p>
<p>You can only assign the setuid/setgid bit by explicitly defining permissions. The character for the setuid/setguid bit is s.</p>
<p>So do set the setuid/setguid bit on file2.sh you would issue the command chmod g+s file2.sh.</p>
<p>Sticky Bit Special Permissions</p>
<p>The sticky bit can be very useful in shared environment because when it has been assigned to the permissions on a directory it sets it so only file owner can rename or delete the said file.</p>
<p>You can only assign the sticky bit by explicitly defining permissions. The character for the sticky bit is t.</p>
<p>To set the sticky bit on a directory named dir1 you would issue the command chmod +t dir1.<br />
When Permissions Are Important</p>
<p>To some users of Mac- or Windows-based computers you don&#8217;t think about permissions, but those environments don&#8217;t focus so aggressively on user based rights on files unless you are in a corporate environment. But now you are running a Linux-based system and permission based security is simplified and can be easily used to restrict access as you please.</p>
<p>So I will show you some documents and folders that you want to focus on and show you how the optimal permissions should be set.</p>
<p>home directories &#8211; The users\&#8217; home directories are important because you do not want other users to be able to view and modify the files in another user\&#8217;s documents of desktop. To remedy this you will want the directory to have the drwx______ (700) permissions, so lets say we want to enforce the correct permissions on the user user1\&#8217;s home directory that can be done by issuing the command chmod 700 /home/user1.<br />
bootloader configuration files &#8211; If you decide to implement password to boot specific operating systems then you will want to remove read and write permissions from the configuration file from all users but root. To do you can change the permissions of the file to 700.<br />
system and daemon configuration files &#8211; It is very important to restrict rights to system and daemon configuration files to restrict users from editing the contents, it may not be advisable to restrict read permissions, but restricting write permissions is a must. In these cases it may be best to modify the rights to 644.<br />
firewall scripts &#8211; It may not always be necessary to block all users from reading the firewall file, but it is advisable to restrict the users from writing to the file. In this case the firewall script is run by the root user automatically on boot, so all other users need no rights, so you can assign the 700 permissions.</p>
<p>Other examples can be given, but this article is already very lengthy, so if you want to share other examples of needed restrictions please do so in the comments.<br />
Comments Welcome</p>
<p>If you have anything to add or want to make a comment or correction please do so in the comments. I look forward to your feedback and wish you the best in your future with Linux-based systems.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.emblogic.com/blog/06/understanding-file-permission/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CHARACTER DRIVER(BLOCKING I/O)</title>
		<link>https://www.emblogic.com/blog/06/character-driverblocking-io/</link>
		<comments>https://www.emblogic.com/blog/06/character-driverblocking-io/#comments</comments>
		<pubDate>Thu, 05 Jun 2014 07:55:29 +0000</pubDate>
		<dc:creator><![CDATA[gkarya1990]]></dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.emblogic.com/blog/?p=10330</guid>
		<description><![CDATA[Linux has the wait_queue_head_t data structure for implementing blocking I/O operations. A process that wants to wait for a condition can call either of the following wait_event_xxx() functions: wait_event() wait_event_interruptible() wait_event_timeout() wait_event_interruptible_timeout() wait_event_interruptible_exclusive() The first four API’s will result in &#8230; <a href="https://www.emblogic.com/blog/06/character-driverblocking-io/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p style="text-align: justify">Linux has the wait_queue_head_t data structure for implementing blocking I/O operations. A process that wants to wait for a condition can call either of the following wait_event_xxx() functions:</p>
<ul style="text-align: justify">
<li><span style="line-height: 14px">wait_event()</span></li>
<li>wait_event_interruptible()</li>
<li>wait_event_timeout()</li>
<li>wait_event_interruptible_timeout()</li>
<li>wait_event_interruptible_exclusive()</li>
</ul>
<p style="text-align: justify">The first four API’s will result in a<strong> non-exclusive wait</strong>. The last API will result in a <strong>exclusive wait</strong>.</p>
<p style="text-align: justify">There are some interesting facts to be noted about the corresponding wake_up_xxx() functions.</p>
<ol style="text-align: justify">
<li><span style="line-height: 1.714285714;font-size: 1rem">The wake_up(queue) and wake_up_interruptible(queue) functions will wake up all the non exclusive processes + one exclusive process waiting on the queue and whose wait condition is satisfied.</span></li>
<li>The wake_up_nr(queue, nr) and wake_up_interruptible(queue, nr) functions will wake up all the non exclusive processes + upto ‘nr’ exclusive processes waiting on the queue and whose wait conditions are satisfied.</li>
<li>The wake_up_all(queue) and wake_up_interruptible_all(queue) functions will wake up all the non exclusive processes + all exclusive processes waiting on the queue and whose wait conditions are satisfied.</li>
</ol>
<p style="text-align: justify"><span style="line-height: 1.714285714;font-size: 1rem">Considering that we are not interested in ‘exclusive’ wait, let us analyze following two programs:</span></p>
<p style="text-align: justify"><strong style="line-height: 1.714285714;font-size: 1rem">Program 1: Using wake_up() calls without delays</strong></p>
<p style="text-align: justify"><a href="http://www.embeddedveda.com/programming_code.php?example_title=example_wake_up&amp;example1=./code/drivers/99_interesting_programs/example_wake_up.c">example_wake_up.c</a> is a program that implements the following functionality:</p>
<ul style="text-align: justify">
<li><span style="line-height: 14px"><strong>read()</strong> function that is blocked for data using the <strong>wait_event_interruptible()</strong> call.</span></li>
<li><strong>write()</strong> function that copies some data and then calls the <strong>wake_up_interruptible()</strong> call.</li>
</ul>
<p style="text-align: justify">In order to test this program, perform the following operations:</p>
<ul style="text-align: justify">
<li><span style="line-height: 14px">Insert the example_wake_up.ko module into the kernel using the <strong>insmod</strong> utility.</span></li>
<li>Create a /dev/simple_char_dev entry using the <strong>mknod</strong> utility.</li>
<li>Open a terminal and execute ‘<strong>cat /dev/simple_char_dev</strong>‘.</li>
<li>Open another terminal and execute ‘<strong>cat /dev/simple_char_dev</strong>‘.</li>
<li>Now in another terminal, execute the ‘<strong>echo “hello world for wake up testing” &gt; /dev/simple_char_dev</strong>‘.</li>
<li>You will notice that <span style="text-decoration: underline"><strong>only one</strong></span> of the ‘cat’ programs will get the data. The other ‘cat’ program waits for data.</li>
</ul>
<p style="text-align: justify"><strong>Program 2: Using wake_up() calls with delay</strong></p>
<p style="text-align: justify"><a href="http://www.embeddedveda.com/programming_code.php?example_title=example_wake_up_delay&amp;example1=./code/drivers/99_interesting_programs/example_wake_up_delay.c">example_wake_up_delay.c</a> is a program that implements the following functionality:</p>
<ul style="text-align: justify">
<li><strong>read()</strong> function that is blocked for data using the <strong>wait_event_interruptible()</strong> call.</li>
<li><strong style="line-height: 1.714285714;font-size: 1rem">write()</strong><span style="line-height: 1.714285714;font-size: 1rem"> function that copies some data and then calls the </span><strong style="line-height: 1.714285714;font-size: 1rem">wake_up_interruptible()</strong><span style="line-height: 1.714285714;font-size: 1rem"> call.</span></li>
<li>On wake up, the <strong>read()</strong> functions sleeps for one second before resetting the ‘wait condition’.</li>
</ul>
<p style="text-align: justify">In order to test this program, perform the following operations:</p>
<ul style="text-align: justify">
<li>Insert the example_wake_up.ko module into the kernel using the <strong>insmod</strong> utility.</li>
<li>Create a /dev/simple_char_dev entry using the <strong>mknod</strong> utility.</li>
<li>Open a terminal and execute ‘<strong>cat /dev/simple_char_dev</strong>‘.</li>
<li>Open another terminal and execute ‘<strong>cat /dev/simple_char_dev</strong>‘.</li>
<li>Now in another terminal, execute the ‘<strong>echo “hello world for wake up testing” &gt; /dev/simple_char_dev</strong>‘.</li>
<li>You will notice that <span style="text-decoration: underline"><strong>both</strong></span> the ‘cat’ programs will get the data.</li>
</ul>
<p style="text-align: justify"><strong>Reason:</strong></p>
<p style="text-align: justify">The above behavior is due the following facts about the wake_up() functions:</p>
<ol style="text-align: justify">
<li><span style="line-height: 14px">The ‘cat’ program is waiting in the read() function.</span></li>
<li>The ‘echo’ program provides some data and calls the wake_up() function.</li>
<li>As a result of the wake_up() function, a sleeping process can move to executing state and can get executed before the wake_up() function returns.</li>
<li>Without the delay, the first ‘cat’ program to wake up consumes the data and resets the condition.</li>
<li>When the wake_up() function continues to execute, it finds that the condition is already false. Hence it does not wake up any more processes.</li>
<li>With the delay before resetting the condition, the wake_up() function call will wake up all the processes.</li>
</ol>
<p style="text-align: justify">
]]></content:encoded>
			<wfw:commentRss>https://www.emblogic.com/blog/06/character-driverblocking-io/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DISK PARTITION</title>
		<link>https://www.emblogic.com/blog/06/disk-partition/</link>
		<comments>https://www.emblogic.com/blog/06/disk-partition/#comments</comments>
		<pubDate>Sun, 01 Jun 2014 17:02:55 +0000</pubDate>
		<dc:creator><![CDATA[gkarya1990]]></dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.emblogic.com/blog/?p=10256</guid>
		<description><![CDATA[Primary Partition, Logical Partition and Extended Partition (Disk Partition Basic) A disk partition is a defined storage space on a hard drive. All Windows operating systems can let users divide a hard disk into multiple partitions, in this way, making &#8230; <a href="https://www.emblogic.com/blog/06/disk-partition/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<h1>Primary Partition, Logical Partition and Extended Partition (Disk Partition Basic)</h1>
<p>A disk partition is a defined storage space on a hard drive. All Windows operating systems can let users divide a hard disk into multiple partitions, in this way, making one physical hard disk into several smaller logical partitions. To store classified data, multiple partitions on a disk can organize his data more effectively. On Microsoft Windows system, the OS was installed in one partition and other some partition is created to store user data, documents or games. This benefit is when a problem occurs with Windows system; the OS partition can be totally destroyed and reinstalled, but this does not affect the data partition.</p>
<p>Some users may split a hard disk into multiple partitions because smaller partitions offer smaller cluster sizes. A cluster size is the smallest chunk of data which a partition can store. A large partition might have a cluster size of 64KB. This means that a file with one word in it will occupy 64KB of space on the disk. In a smaller partition, that file might only require 2KB to store. This is a useful policy if you need to save a large number of small files.</p>
<p>You can create, delete and format partition through using the diskpart.exe command. Many operating systems also have graphical tools which accomplish the same task such as Partition Assistant. The <a href="http://www.disk-partition.com/free-partition-manager.html"><b>Partition Assistant</b></a> is a free partition manager. It not only can partition on a disk, but also resize/move a partition to adjust the size of the partition to optimize disk space usage.<br />
The following is Disk Partition Related Glossary</p>
<p><b>Primary Partition and Active Partition: </b><br />
A primary partition is in which an Operating System can be installed. One hard disk may contain a maximum of 4 primary partitions. An active partition is based on primary partition. Any one of the 4 primary partitions can be set as active partition. Since there can be 4 primary partitions with 4 different Operating Systems installed, one of the partition that is marked active is used for the initial booting. The active partition contains the boot loader (such as ntldr or bootmgr) to load operating systems from a disk.</p>
<p><b>Extended Partition and Logical Partition:</b><br />
Because the primary only can be created four maximum, this need to use extended partition to break the limitation of 4 partitions. In an Extended Partition you can create unlimited logical partition. You can store data in the logical partitions similar with primary partition, but the extended partition is not used to store data, because the Extended Partition is used to hold logical partitions, at the same time, there is one extended partition on a disk.</p>
<p><b>Partition Table:</b><br />
Partition Table is a storage space which records some information about primary, extended and logical partitions. Further, the create/delete/resize of any partition all will modify the partition table to reflect the changes permanently. If partition table is crashed by virus or other stuffs, you partition will lost, so the table is extremely important.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.emblogic.com/blog/06/disk-partition/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>linux OS&#8230;Why so important</title>
		<link>https://www.emblogic.com/blog/05/linux-os-why-so-important/</link>
		<comments>https://www.emblogic.com/blog/05/linux-os-why-so-important/#comments</comments>
		<pubDate>Mon, 19 May 2014 16:59:41 +0000</pubDate>
		<dc:creator><![CDATA[gkarya1990]]></dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.emblogic.com/blog/?p=10148</guid>
		<description><![CDATA[Why Linux is the Best Operation System Welcome To LinuxShark, LinuxShark is based on OpenSuSE, With the award winning GNOME Desktop (option to add KDE avaliable) . Updated regularly with the latest security patches and kernel builds. Keeping you safe &#8230; <a href="https://www.emblogic.com/blog/05/linux-os-why-so-important/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<h1>Why Linux is the Best Operation System</h1>
<p>Welcome To LinuxShark,</p>
<p>LinuxShark is based on OpenSuSE, With the award winning GNOME Desktop (option to add KDE avaliable) .</p>
<p>Updated regularly with the latest security patches and kernel builds. Keeping you safe all the time !</p>
<p>What More ??… Download LinuxShark Today And Explore !</p>
<p><img class="alignright size-full wp-image-11" title="tux" src="http://linuxshark.info/wp-content/uploads/2012/02/tux.jpg" alt="" width="300" height="300" />For non-techie computer users, choosing the best operating system can be a daunting, if not frustrating, exercise. How do you choose between the obvious options Windows 7 and Mac OS X? Better yet, how does Linux stack up against these popular options? More to the point, why are many computer experts touting the versatility and robustness of Linux over the more mainstream Windows and Mac? Could it really be possible that while Windows and Mac OS X lead in terms of popularity among the non-computer experts, Linux has quietly grabbed the distinction as the best operating system out in the market?</p>
<p>In this post, we will talk about the main features of Linux with the added explanation as to why experts indeed consider it as the best operating system available. You’d be surprised to know the limitations of Windows 7 and Mac OS X and how Linux adequately meets these limitations without compromising its ability to match the expected functions of the more established brands.</p>
<p>The best feature of Linux operating systems is its low susceptibility to virus and malware infestation. If you have been a Windows user for a long time, you would know how problematic Windows is when it comes to viruses. With Linux, you are spared from all the hassle of having to constantly update your anti-virus software or scan your computer every so often.</p>
<p>Linux is almost always a free operating system with multiple sources distribution. In contrast, Windows and Mac OS X are some of the most expensive operating systems available. If you want to cut on costs, you can definitely benefit from choosing Linux for your everyday needs.</p>
<p>Linux is an open source platforms with plenty of developers working on applications, functions, features and add-ons that are guaranteed to improve your user experience. Contrary to popular belief, many Linux functions rival those of Windows and Mac OS. All that you need to do is try it out for a couple of weeks to personally see for yourself how Linux is so much better than many perceive it to be.</p>
<p>One of the most important reasons why computer-savvy individuals consider Linux as the best operating system is because it is far more customizable than its popular counterparts. With Windows and Mac, there are plenty of restrictions that limit what you can do to the OS. This is not easily noticeable to the average computer user but if you are planning to do plenty of customizations, Linux is undoubtedly the best operating system for this purpose.<br />
If you do not want to ditch your Windows applications but would want to give Linux a try, there are many compatibility programs that allow Linux to run Windows programs like Word, Excel, and PowerPoint. You can run programs like Wine to load Microsoft Office programs and still enjoy the many benefits of Linux as the underlying operating system.</p>
<p>Low resource requirements. Ever notice how Windows hangs up after a few years of use? As your computer gets older, it demands more resources such as RAM eventually slowing down your system. With Linux’s low-resource approach, you are less likely to encounter slower load times.</p>
<p>These reasons highlight the versatility and strength of Linux operating systems and easily explain why it is the best operating system on the market. Give it a shot and find out for yourself how Linux can make your life so much simpler without altering your computer usage habits and undermining your computer’s performance.</p>
<h2>Why Did Dell Just Launch A Line of Linux Laptops?</h2>
<p>Actually what you may not know is that Dell has actually been selling Linux laptops since 2007, but stopped marketing them when their general users found Linux too difficult to use.</p>
<p>Even though they stopped the promotion of Linux machines, plenty were still being sold around the globe and now they are back due to popular demand. Dell does say that their marketing efforts will clearly states these Linux machines are for power users only.</p>
<p>Linux has been around for a number of years with many users swearing by the operating system, those that are used to Windows machines often find Ubuntu very difficult to lose, much like when you try to lose weight, it feels impossible but once you get into the rhythm of healthy eating the weight drops off.</p>
<p>This operating system is exceptionally versatile, enabling users with computer knowledge to tailor it to their specific needs, there are thousands of forums online with suggestions and help, and you find them the same way you would if you were to search for Gibson les Paul or phen375 reviews.</p>
<p>Dell has also set up an information section on their website to help users come to grips with the Linux system. The Dell laptops will not offer dual booting, which means you cannot have Windows running, but they will accommodation a Windows version of the operating system, you can visit website to find out more.</p>
<h2>What Makes Linux So Popular?</h2>
<p>Besides demand, Dell has chosen to use Linux on their machines because the software is so affordable, this means lower priced laptops to the public. The machines will be able to run faster and smoother than they do with Windows with less frustrating updates.</p>
<p>Linux offers a choice of benefits from affordability and flexibility to excellent packages including word processing, spreadsheets and more.</p>
<p>Once you get the hang of the Linux program it is really easy to use, those that have been using it for years will tell you it far outweighs Windows, but for Windows users it’s a little more complicated than that.</p>
<p>Linux machines enable you to ensure excellent reputation management online by tailoring your operating system to meet your specific demands. You can find out more information on these machines when you click for source.</p>
<p>Overall it has to be agreed that demand has brought these great operating system back to the Dell laptops, they couldn’t ignore the fact that their Linux machines were still selling and in high demand, yet they were not advertising them anymore, actually they stopped advertising them back in 2010 and yet they were still selling.</p>
<p>In order to keep up with the times, Dell has had to take the client demands into consideration before losing the power user side of the market. The same as you can test an example url, but it’s no use if you don’t have the specific target audience clicking on it.</p>
<p>It will be exciting to see how these new Linux Dell Laptops do and how well they sell once they are introduced onto the market.</p>
<h2>Is Linux Right For You?</h2>
<p>When you purchase a new computer these days you have choices on whether to go with the system on the machine or sold separately which can cost a small fortune or to go for Linux.</p>
<p>Now the one thing you need to realize is that initially you will struggle to find your way around Linux, especially if you are used to using Windows, but there are some advantages of Linux that may help you determine whether it is the right operating system for you.</p>
<h2><strong>Affordable</strong></h2>
<p>If you’re basing your decision on price, then Linux is right for you. There is no comparing Windows to Linux when it comes to money; we all know that Windows is expensive, while Linux can be obtained free, a huge cost saving in anyone’s book. All you have to do is go to the webpage and click where it says click here and you have Linux ready to go.</p>
<h2><strong>Security</strong></h2>
<p>Another known fact about Linux is their security is much stronger than other operating systems; you don’t need home security systems for your computer when you use the Linux system, and you can browse the net without any serious concerns.</p>
<h2><strong>Versatility</strong></h2>
<p>The biggest plus for me when it comes to Linux is the ability for me to change what I want and how I want it especially on my desktop, the versatility is easy and amazing and I’m not forced to go with the design given to me. It’s similar to when you are shopping around for remodeling estimates, but you know exactly what you want and don’t need someone deciding for you.</p>
<h2><strong>Fast and Efficient</strong></h2>
<p>Another interesting fact about Linux is how fast and effective it is, it’s the ideal solution for an older computer which struggles with other operating systems, it is much faster is start up to browsing. It’s like the hcg drops you buy when trying to lose weight, super-fast and super effective, you can think of it as the anti wrinkle cream for older computers to get them running smoothly again.</p>
<h2>What Else You Need To Know</h2>
<p>Now it is true that when you load Linux onto a machine for the first time you may find it difficult to navigate and get around, this is because it’s something new, something you’re not used to. Once you get the hang of it, it can be very rewarding and offer you many features and benefits you never dreamed possible.</p>
<p>Think of Linux as umbrella companies, they come in to protect and help you when other operating systems fail. You don’t need a digital agency to help you operate your computer and it’s not as hard a work as a pullup bar in the gym.</p>
<p>You need to also take into account that Linux comes with a choice of bundled software including their own word-processing and spreadsheet programs, so you can still do everything you used to do before. Easy and fast internet search engines where you can easily search for <a href="http://www.westcoastflooring.com/blog">San Marcos Flooring</a> or ACN-INC without any problems.</p>
<h4>Why Linux is a Great Operating System</h4>
<p>When you get a new computer you have such a selection of operating systems to choose from. There is Windows, MAC and then Linux. Linux tends to be the more popular and has been voted the best operating system, but why?</p>
<p>Firstly Linux is affordable, often it’s completely free. This is a huge draw card for many people. The other operating systems are expensive and they also tend to suffer with viruses and constant updates, which are frustrating to say the least. You don’t need a finance mba online degree to know that finding a free operating system is a huge saving, especially when you have just paid out for a new PC.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.emblogic.com/blog/05/linux-os-why-so-important/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CROSS COMPILATION  VS NATIVE  COMPILATION</title>
		<link>https://www.emblogic.com/blog/04/cross-compilation-vs-native-compilation/</link>
		<comments>https://www.emblogic.com/blog/04/cross-compilation-vs-native-compilation/#comments</comments>
		<pubDate>Wed, 16 Apr 2014 06:21:06 +0000</pubDate>
		<dc:creator><![CDATA[gkarya1990]]></dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.emblogic.com/blog/?p=9818</guid>
		<description><![CDATA[By default, Linux builds for the same architecture the host system is running. This is called &#8220;native compiling&#8221;. An x86 system building an x86 kernel, x86-64 building x86-64, or powerpc building powerpc are all examples of native compiling. Building different &#8230; <a href="https://www.emblogic.com/blog/04/cross-compilation-vs-native-compilation/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>By default, Linux builds for the same architecture the host system is running. This is called &#8220;native compiling&#8221;. An x86 system building an x86 kernel, x86-64 building x86-64, or powerpc building powerpc are all examples of native compiling.</p>
<p>Building different binaries than the host runs is called cross compiling. <a href="http://landley.net/writing/docs/cross-compiling.html">Cross compiling is hard</a>. The build system for the Linux kernel supports cross compiling via a two step process: 1) Specify a different architecture (ARCH) during the configure, make, and install stages. 2) Supply a cross compiler (CROSS_COMPILE) which can output the correct kind of binary code. An example cross compile command line (building the &#8220;arm&#8221; architecture) looks like:</p>
<blockquote>
<pre>make ARCH=arm menuconfig
make ARCH=arm CROSS_COMPILE=armv5l-</pre>
</blockquote>
<p>To specify a different architecture than the host, either define the &#8220;ARCH&#8221; environment variable or else add &#8220;ARCH=xxx&#8221; to the make command line for each of the make config, make, and make install stages. The acceptable values for ARCH are the names of the directories in the &#8220;arch&#8221; subdirectory of the Linux kernel source code, see <a href="https://www.kernel.org/doc/index-old.html#Architectures">Architectures</a> for details. All stages of the build must use the same ARCH value, and building a second architecture in the same source directory requires &#8220;make distclean&#8221;. (Just &#8220;make clean&#8221; isn&#8217;t sufficient, things like the include/asm symlink need to be removed and recreated.)</p>
<p>To specify a cross compiler prefix, define the CROSS_COMPILE environment variable (or add CROSS_COMPILE= to each make command line). Native compiler tools, which output code aimed at the environment they&#8217;re running in, usually have a simple name (&#8220;gcc&#8221;, &#8220;ld&#8221;, &#8220;strip&#8221;). Cross compilers usually add a prefix to the name of each tool, indicating the target they produce code for. To tell the Linux kernel build to use a cross compiler named &#8220;armv4l-gcc&#8221; (and corresponding &#8220;armv4l-ld&#8221; and &#8220;armv4l-strip&#8221;) specify &#8220;CROSS_COMPILE=armv4l-&#8221;. (Prefixes ending in a dash are common, and forgetting the trailing dash in CROSS_COMPILE is a common mistake.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.emblogic.com/blog/04/cross-compilation-vs-native-compilation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PUZZLE&#8230;Can you print anything without using semicolon(;)..?</title>
		<link>https://www.emblogic.com/blog/03/puzzle-can-you-print-anything-without-using-semicolon/</link>
		<comments>https://www.emblogic.com/blog/03/puzzle-can-you-print-anything-without-using-semicolon/#comments</comments>
		<pubDate>Sat, 29 Mar 2014 16:34:02 +0000</pubDate>
		<dc:creator><![CDATA[gkarya1990]]></dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.emblogic.com/blog/?p=9662</guid>
		<description><![CDATA[here is code&#8230; int main() {if(printf(&#8220;hello&#8221;)) }]]></description>
				<content:encoded><![CDATA[<p>here is code&#8230;</p>
<p>int main()</p>
<p>{if(printf(&#8220;hello&#8221;))</p>
<p>}</p>
]]></content:encoded>
			<wfw:commentRss>https://www.emblogic.com/blog/03/puzzle-can-you-print-anything-without-using-semicolon/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>BEST ways to implement C code!!!!!!!!!!!!</title>
		<link>https://www.emblogic.com/blog/03/best-ways-to-implement-c-code/</link>
		<comments>https://www.emblogic.com/blog/03/best-ways-to-implement-c-code/#comments</comments>
		<pubDate>Sun, 23 Mar 2014 06:01:26 +0000</pubDate>
		<dc:creator><![CDATA[gkarya1990]]></dc:creator>
				<category><![CDATA[Data Structures with C]]></category>

		<guid isPermaLink="false">http://www.emblogic.com/blog/?p=9285</guid>
		<description><![CDATA[5.1 Formatting Your Source Code Please keep the length of source lines to 79 characters or less, for maximum readability in the widest range of environments. It is important to put the open-brace that starts the body of a C &#8230; <a href="https://www.emblogic.com/blog/03/best-ways-to-implement-c-code/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<h3>5.1 Formatting Your Source Code</h3>
<p><a name="index-formatting-source-code"></a> <a name="index-line-length"></a> <a name="index-length-of-source-lines"></a></p>
<p>Please keep the length of source lines to 79 characters or less, for maximum readability in the widest range of environments.</p>
<p><a name="index-open-brace"></a> <a name="index-braces_002c-in-C-source"></a> <a name="index-function-definitions_002c-formatting"></a></p>
<p>It is important to put the open-brace that starts the body of a C function in column one, so that they will start a defun. Several tools look for open-braces in column one to find the beginnings of C functions. These tools will not work on code not formatted that way.</p>
<p>Avoid putting open-brace, open-parenthesis or open-bracket in column one when they are inside a function, so that they won’t start a defun. The open-brace that starts a <code>struct</code> body can go in column one if you find it useful to treat that definition as a defun.</p>
<p>It is also important for function definitions to start the name of the function in column one. This helps people to search for function definitions, and may also help certain tools recognize them. Thus, using Standard C syntax, the format is this:</p>
<div>
<pre>static char *
concat (char *s1, char *s2)
{
  …
}</pre>
</div>
<p>or, if you want to use traditional C syntax, format the definition like this:</p>
<div>
<pre>static char *
concat (s1, s2)        /* Name starts in column one here */
     char *s1, *s2;
{                     /* Open brace in column one here */
  …
}</pre>
</div>
<p>In Standard C, if the arguments don’t fit nicely on one line, split it like this:</p>
<div>
<pre>int
lots_of_args (int an_integer, long a_long, short a_short,
              double a_double, float a_float)
…</pre>
</div>
<p><a name="index-struct-types_002c-formatting"></a> <a name="index-enum-types_002c-formatting"></a></p>
<p>For <code>struct</code> and <code>enum</code> types, likewise put the braces in column one, unless the whole contents fits on one line:</p>
<div>
<pre>struct foo
{
  int a, b;
}</pre>
<pre>or</pre>
<pre>struct foo { int a, b; }</pre>
</div>
<p>The rest of this section gives our recommendations for other aspects of C formatting style, which is also the default style of the <code>indent</code> program in version 1.2 and newer. It corresponds to the options</p>
<div>
<pre>-nbad -bap -nbc -bbo -bl -bli2 -bls -ncdb -nce -cp1 -cs -di2
-ndj -nfc1 -nfca -hnl -i2 -ip5 -lp -pcs -psl -nsc -nsob</pre>
</div>
<p>We don’t think of these recommendations as requirements, because it causes no problems for users if two different programs have different formatting styles.</p>
<p>But whatever style you use, please use it consistently, since a mixture of styles within one program tends to look ugly. If you are contributing changes to an existing program, please follow the style of that program.</p>
<p>For the body of the function, our recommended style looks like this:</p>
<div>
<pre>if (x &lt; foo (y, z))
  haha = bar[4] + 5;
else
  {
    while (z)
      {
        haha += foo (z, z);
        z--;
      }
    return ++x + bar ();
  }</pre>
</div>
<p><a name="index-spaces-before-open_002dparen"></a></p>
<p>We find it easier to read a program when it has spaces before the open-parentheses and after the commas. Especially after the commas.</p>
<p>When you split an expression into multiple lines, split it before an operator, not after one. Here is the right way:</p>
<p><a name="index-expressions_002c-splitting"></a></p>
<div>
<pre>if (foo_this_is_long &amp;&amp; bar &gt; win (x, y, z)
    &amp;&amp; remaining_condition)</pre>
</div>
<p>Try to avoid having two operators of different precedence at the same level of indentation. For example, don’t write this:</p>
<div>
<pre>mode = (inmode[j] == VOIDmode
        || GET_MODE_SIZE (outmode[j]) &gt; GET_MODE_SIZE (inmode[j])
        ? outmode[j] : inmode[j]);</pre>
</div>
<p>Instead, use extra parentheses so that the indentation shows the nesting:</p>
<div>
<pre>mode = ((inmode[j] == VOIDmode
         || (GET_MODE_SIZE (outmode[j]) &gt; GET_MODE_SIZE (inmode[j])))
        ? outmode[j] : inmode[j]);</pre>
</div>
<p>Insert extra parentheses so that Emacs will indent the code properly. For example, the following indentation looks nice if you do it by hand,</p>
<div>
<pre>v = rup-&gt;ru_utime.tv_sec*1000 + rup-&gt;ru_utime.tv_usec/1000
    + rup-&gt;ru_stime.tv_sec*1000 + rup-&gt;ru_stime.tv_usec/1000;</pre>
</div>
<p>but Emacs would alter it. Adding a set of parentheses produces something that looks equally nice, and which Emacs will preserve:</p>
<div>
<pre>v = (rup-&gt;ru_utime.tv_sec*1000 + rup-&gt;ru_utime.tv_usec/1000
     + rup-&gt;ru_stime.tv_sec*1000 + rup-&gt;ru_stime.tv_usec/1000);</pre>
</div>
<p>Format do-while statements like this:</p>
<div>
<pre>do
  {
    a = foo (a);
  }
while (a &gt; 0);</pre>
</div>
<p><a name="index-formfeed"></a> <a name="index-control_002dL"></a></p>
<p>Please use formfeed characters (control-L) to divide the program into pages at logical places (but not within a function). It does not matter just how long the pages are, since they do not have to fit on a printed page. The formfeeds should appear alone on lines by themselves.</p>
<hr />
<p><a name="Comments"></a></p>
<div>
<p>Next: <a href="http://www.gnu.org/prep/standards/standards.html#Syntactic-Conventions" rel="next">Syntactic Conventions</a>, Previous: <a href="http://www.gnu.org/prep/standards/standards.html#Formatting" rel="prev">Formatting</a>, Up: <a href="http://www.gnu.org/prep/standards/standards.html#Writing-C" rel="up">Writing C</a>   [<a title="Table of contents" href="http://www.gnu.org/prep/standards/standards.html#SEC_Contents" rel="contents">Contents</a>][<a title="Index" href="http://www.gnu.org/prep/standards/standards.html#Index" rel="index">Index</a>]</p>
</div>
<p><a name="Commenting-Your-Work"></a></p>
<h3>5.2 Commenting Your Work</h3>
<p><a name="index-commenting"></a></p>
<p>Every program should start with a comment saying briefly what it is for. Example: ‘fmt &#8211; filter for simple filling of text’. This comment should be at the top of the source file containing the ‘main’ function of the program.</p>
<p>Also, please write a brief comment at the start of each source file, with the file name and a line or two about the overall purpose of the file.</p>
<p>Please write the comments in a GNU program in English, because English is the one language that nearly all programmers in all countries can read. If you do not write English well, please write comments in English as well as you can, then ask other people to help rewrite them. If you can’t write comments in English, please find someone to work with you and translate your comments into English.</p>
<p>Please put a comment on each function saying what the function does, what sorts of arguments it gets, and what the possible values of arguments mean and are used for. It is not necessary to duplicate in words the meaning of the C argument declarations, if a C type is being used in its customary fashion. If there is anything nonstandard about its use (such as an argument of type <code>char *</code> which is really the address of the second character of a string, not the first), or any possible values that would not work the way one would expect (such as, that strings containing newlines are not guaranteed to work), be sure to say so.</p>
<p>Also explain the significance of the return value, if there is one.</p>
<p>Please put two spaces after the end of a sentence in your comments, so that the Emacs sentence commands will work. Also, please write complete sentences and capitalize the first word. If a lower-case identifier comes at the beginning of a sentence, don’t capitalize it! Changing the spelling makes it a different identifier. If you don’t like starting a sentence with a lower case letter, write the sentence differently (e.g., “The identifier lower-case is …”).</p>
<p>The comment on a function is much clearer if you use the argument names to speak about the argument values. The variable name itself should be lower case, but write it in upper case when you are speaking about the value rather than the variable itself. Thus, “the inode number NODE_NUM” rather than “an inode”.</p>
<p>There is usually no purpose in restating the name of the function in the comment before it, because readers can see that for themselves. There might be an exception when the comment is so long that the function itself would be off the bottom of the screen.</p>
<p>There should be a comment on each static variable as well, like this:</p>
<div>
<pre>/* Nonzero means truncate lines in the display;
   zero means continue them.  */
int truncate_lines;</pre>
</div>
<p><a name="index-conditionals_002c-comments-for"></a> <a name="index-_0023endif_002c-commenting"></a></p>
<p>Every ‘#endif’ should have a comment, except in the case of short conditionals (just a few lines) that are not nested. The comment should state the condition of the conditional that is ending, <em>including its sense</em>. ‘#else’ should have a comment describing the condition <em>and sense</em> of the code that follows. For example:</p>
<div>
<pre>#ifdef foo
  …
#else /* not foo */
  …
#endif /* not foo */</pre>
<pre>#ifdef foo
  …
#endif /* foo */</pre>
</div>
<p>but, by contrast, write the comments this way for a ‘#ifndef’:</p>
<div>
<pre>#ifndef foo
  …
#else /* foo */
  …
#endif /* foo */</pre>
<pre>#ifndef foo
  …
#endif /* not foo */</pre>
</div>
<hr />
<p><a name="Syntactic-Conventions"></a></p>
<div>
<p>Next: <a href="http://www.gnu.org/prep/standards/standards.html#Names" rel="next">Names</a>, Previous: <a href="http://www.gnu.org/prep/standards/standards.html#Comments" rel="prev">Comments</a>, Up: <a href="http://www.gnu.org/prep/standards/standards.html#Writing-C" rel="up">Writing C</a>   [<a title="Table of contents" href="http://www.gnu.org/prep/standards/standards.html#SEC_Contents" rel="contents">Contents</a>][<a title="Index" href="http://www.gnu.org/prep/standards/standards.html#Index" rel="index">Index</a>]</p>
</div>
<p><a name="Clean-Use-of-C-Constructs"></a></p>
<h3>5.3 Clean Use of C Constructs</h3>
<p><a name="index-syntactic-conventions"></a> <a name="index-implicit-int"></a> <a name="index-function-argument_002c-declaring"></a></p>
<p>Please explicitly declare the types of all objects. For example, you should explicitly declare all arguments to functions, and you should declare functions to return <code>int</code> rather than omitting the <code>int</code>.</p>
<p><a name="index-compiler-warnings"></a> <a name="index-_002dWall-compiler-option"></a></p>
<p>Some programmers like to use the GCC ‘-Wall’ option, and change the code whenever it issues a warning. If you want to do this, then do. Other programmers prefer not to use ‘-Wall’, because it gives warnings for valid and legitimate code which they do not want to change. If you want to do this, then do. The compiler should be your servant, not your master.</p>
<p><a name="index-clang"></a> <a name="index-lint"></a></p>
<p>Don’t make the program ugly just to placate static analysis tools such as <code>lint</code>, <code>clang</code>, and GCC with extra warnings options such as-Wconversionand-Wundef. These tools can help find bugs and unclear code, but they can also generate so many false alarms that it hurts readability to silence them with unnecessary casts, wrappers, and other complications. For example, please don’t insert casts to <code>void</code> or calls to do-nothing functions merely to pacify a lint checker.</p>
<p>Declarations of external functions and functions to appear later in the source file should all go in one place near the beginning of the file (somewhere before the first function definition in the file), or else should go in a header file. Don’t put <code>extern</code> declarations inside functions.</p>
<p><a name="index-temporary-variables"></a></p>
<p>It used to be common practice to use the same local variables (with names like <code>tem</code>) over and over for different values within one function. Instead of doing this, it is better to declare a separate local variable for each distinct purpose, and give it a name which is meaningful. This not only makes programs easier to understand, it also facilitates optimization by good compilers. You can also move the declaration of each local variable into the smallest scope that includes all its uses. This makes the program even cleaner.</p>
<p>Don’t use local variables or parameters that shadow global identifiers. GCC’s ‘-Wshadow’ option can detect this problem.</p>
<p><a name="index-multiple-variables-in-a-line"></a></p>
<p>Don’t declare multiple variables in one declaration that spans lines. Start a new declaration on each line, instead. For example, instead of this:</p>
<div>
<pre>int    foo,
       bar;</pre>
</div>
<p>write either this:</p>
<div>
<pre>int foo, bar;</pre>
</div>
<p>or this:</p>
<div>
<pre>int foo;
int bar;</pre>
</div>
<p>(If they are global variables, each should have a comment preceding it anyway.)</p>
<p>When you have an <code>if</code>-<code>else</code> statement nested in another <code>if</code> statement, always put braces around the <code>if</code>-<code>else</code>. Thus, never write like this:</p>
<div>
<pre>if (foo)
  if (bar)
    win ();
  else
    lose ();</pre>
</div>
<p>always like this:</p>
<div>
<pre>if (foo)
  {
    if (bar)
      win ();
    else
      lose ();
  }</pre>
</div>
<p>If you have an <code>if</code> statement nested inside of an <code>else</code> statement, either write <code>else if</code> on one line, like this,</p>
<div>
<pre>if (foo)
  …
else if (bar)
  …</pre>
</div>
<p>with its <code>then</code>-part indented like the preceding <code>then</code>-part, or write the nested <code>if</code> within braces like this:</p>
<div>
<pre>if (foo)
  …
else
  {
    if (bar)
      …
  }</pre>
</div>
<p>Don’t declare both a structure tag and variables or typedefs in the same declaration. Instead, declare the structure tag separately and then use it to declare the variables or typedefs.</p>
<p>Try to avoid assignments inside <code>if</code>-conditions (assignments inside <code>while</code>-conditions are ok). For example, don’t write this:</p>
<div>
<pre>if ((foo = (char *) malloc (sizeof *foo)) == 0)
  fatal ("virtual memory exhausted");</pre>
</div>
<p>instead, write this:</p>
<div>
<pre>foo = (char *) malloc (sizeof *foo);
if (foo == 0)
  fatal ("virtual memory exhausted");</pre>
</div>
<p>This example uses zero without a cast as a null pointer constant. This is perfectly fine, except that a cast is needed when calling a varargs function or when using <code>sizeof</code>.</p>
<hr />
<p><a name="Names"></a></p>
<div>
<p>Next: <a href="http://www.gnu.org/prep/standards/standards.html#System-Portability" rel="next">System Portability</a>, Previous: <a href="http://www.gnu.org/prep/standards/standards.html#Syntactic-Conventions" rel="prev">Syntactic Conventions</a>, Up: <a href="http://www.gnu.org/prep/standards/standards.html#Writing-C" rel="up">Writing C</a>   [<a title="Table of contents" href="http://www.gnu.org/prep/standards/standards.html#SEC_Contents" rel="contents">Contents</a>][<a title="Index" href="http://www.gnu.org/prep/standards/standards.html#Index" rel="index">Index</a>]</p>
</div>
<p><a name="Naming-Variables_002c-Functions_002c-and-Files"></a></p>
<h3>5.4 Naming Variables, Functions, and Files</h3>
<p><a name="index-names-of-variables_002c-functions_002c-and-files"></a></p>
<p>The names of global variables and functions in a program serve as comments of a sort. So don’t choose terse names—instead, look for names that give useful information about the meaning of the variable or function. In a GNU program, names should be English, like other comments.</p>
<p>Local variable names can be shorter, because they are used only within one context, where (presumably) comments explain their purpose.</p>
<p>Try to limit your use of abbreviations in symbol names. It is ok to make a few abbreviations, explain what they mean, and then use them frequently, but don’t use lots of obscure abbreviations.</p>
<p>Please use underscores to separate words in a name, so that the Emacs word commands can be useful within them. Stick to lower case; reserve upper case for macros and <code>enum</code> constants, and for name-prefixes that follow a uniform convention.</p>
<p>For example, you should use names like <code>ignore_space_change_flag</code>; don’t use names like <code>iCantReadThis</code>.</p>
<p>Variables that indicate whether command-line options have been specified should be named after the meaning of the option, not after the option-letter. A comment should state both the exact meaning of the option and its letter. For example,</p>
<div>
<pre>/* Ignore changes in horizontal whitespace (-b).  */
int ignore_space_change_flag;</pre>
</div>
<p>When you want to define names with constant integer values, use <code>enum</code>rather than ‘#define’. GDB knows about enumeration constants.</p>
<p><a name="index-file_002dname-limitations"></a> <a name="index-doschk"></a></p>
<p>You might want to make sure that none of the file names would conflict if the files were loaded onto an MS-DOS file system which shortens the names. You can use the program <code>doschk</code> to test for this.</p>
<p>Some GNU programs were designed to limit themselves to file names of 14 characters or less, to avoid file name conflicts if they are read into older System V systems. Please preserve this feature in the existing GNU programs that have it, but there is no need to do this in new GNU programs. <code>doschk</code> also reports file names longer than 14 characters.</p>
<hr />
<p><a name="System-Portability"></a></p>
<div>
<p>Next: <a href="http://www.gnu.org/prep/standards/standards.html#CPU-Portability" rel="next">CPU Portability</a>, Previous: <a href="http://www.gnu.org/prep/standards/standards.html#Names" rel="prev">Names</a>, Up: <a href="http://www.gnu.org/prep/standards/standards.html#Writing-C" rel="up">Writing C</a>   [<a title="Table of contents" href="http://www.gnu.org/prep/standards/standards.html#SEC_Contents" rel="contents">Contents</a>][<a title="Index" href="http://www.gnu.org/prep/standards/standards.html#Index" rel="index">Index</a>]</p>
</div>
<p><a name="Portability-between-System-Types"></a></p>
<h3>5.5 Portability between System Types</h3>
<p><a name="index-portability_002c-between-system-types"></a></p>
<p>In the Unix world, “portability” refers to porting to different Unix versions. For a GNU program, this kind of portability is desirable, but not paramount.</p>
<p>The primary purpose of GNU software is to run on top of the GNU kernel, compiled with the GNU C compiler, on various types of CPU. So the kinds of portability that are absolutely necessary are quite limited. But it is important to support Linux-based GNU systems, since they are the form of GNU that is popular.</p>
<p>Beyond that, it is good to support the other free operating systems (*BSD), and it is nice to support other Unix-like systems if you want to. Supporting a variety of Unix-like systems is desirable, although not paramount. It is usually not too hard, so you may as well do it. But you don’t have to consider it an obligation, if it does turn out to be hard.</p>
<p><a name="index-autoconf"></a></p>
<p>The easiest way to achieve portability to most Unix-like systems is to use Autoconf. It’s unlikely that your program needs to know more information about the host platform than Autoconf can provide, simply because most of the programs that need such knowledge have already been written.</p>
<p>Avoid using the format of semi-internal data bases (e.g., directories) when there is a higher-level alternative (<code>readdir</code>).</p>
<p><a name="index-non_002dPOSIX-systems_002c-and-portability"></a></p>
<p>As for systems that are not like Unix, such as MSDOS, Windows, VMS, MVS, and older Macintosh systems, supporting them is often a lot of work. When that is the case, it is better to spend your time adding features that will be useful on GNU and GNU/Linux, rather than on supporting other incompatible systems.</p>
<p>If you do support Windows, please do not abbreviate it as “win”. In hacker terminology, calling something a “win” is a form of praise. You’re free to praise Microsoft Windows on your own if you want, but please don’t do this in GNU packages. Instead of abbreviating “Windows” to “win”, you can write it in full or abbreviate it to “woe” or “w”. In GNU Emacs, for instance, we use ‘w32’ in file names of Windows-specific files, but the macro for Windows conditionals is called <code>WINDOWSNT</code>.</p>
<p>It is a good idea to define the “feature test macro” <code>_GNU_SOURCE</code> when compiling your C files. When you compile on GNU or GNU/Linux, this will enable the declarations of GNU library extension functions, and that will usually give you a compiler error message if you define the same function names in some other way in your program. (You don’t have to actually <em>use</em> these functions, if you prefer to make the program more portable to other systems.)</p>
<p>But whether or not you use these GNU extensions, you should avoid using their names for any other meanings. Doing so would make it hard to move your code into other GNU programs.</p>
<hr />
<p><a name="CPU-Portability"></a></p>
<div>
<p>Next: <a href="http://www.gnu.org/prep/standards/standards.html#System-Functions" rel="next">System Functions</a>, Previous: <a href="http://www.gnu.org/prep/standards/standards.html#System-Portability" rel="prev">System Portability</a>, Up: <a href="http://www.gnu.org/prep/standards/standards.html#Writing-C" rel="up">Writing C</a>   [<a title="Table of contents" href="http://www.gnu.org/prep/standards/standards.html#SEC_Contents" rel="contents">Contents</a>][<a title="Index" href="http://www.gnu.org/prep/standards/standards.html#Index" rel="index">Index</a>]</p>
</div>
<p><a name="Portability-between-CPUs"></a></p>
<h3>5.6 Portability between CPUs</h3>
<p><a name="index-data-types_002c-and-portability"></a> <a name="index-portability_002c-and-data-types"></a></p>
<p>Even GNU systems will differ because of differences among CPU types—for example, difference in byte ordering and alignment requirements. It is absolutely essential to handle these differences. However, don’t make any effort to cater to the possibility that an <code>int</code> will be less than 32 bits. We don’t support 16-bit machines in GNU.</p>
<p>Similarly, don’t make any effort to cater to the possibility that <code>long</code> will be smaller than predefined types like <code>size_t</code>. For example, the following code is ok:</p>
<div>
<pre>printf ("size = %lu\n", (unsigned long) sizeof array);
printf ("diff = %ld\n", (long) (pointer2 - pointer1));</pre>
</div>
<p>1989 Standard C requires this to work, and we know of only one counterexample: 64-bit programs on Microsoft Windows. We will leave it to those who want to port GNU programs to that environment to figure out how to do it.</p>
<p>Predefined file-size types like <code>off_t</code> are an exception: they are longer than <code>long</code> on many platforms, so code like the above won’t work with them. One way to print an <code>off_t</code> value portably is to print its digits yourself, one by one.</p>
<p>Don’t assume that the address of an <code>int</code> object is also the address of its least-significant byte. This is false on big-endian machines. Thus, don’t make the following mistake:</p>
<div>
<pre>int c;
…
while ((c = getchar ()) != EOF)
  write (file_descriptor, &amp;c, 1);</pre>
</div>
<p>Instead, use <code>unsigned char</code> as follows. (The <code>unsigned</code> is for portability to unusual systems where <code>char</code> is signed and where there is integer overflow checking.)</p>
<div>
<pre>int c;
while ((c = getchar ()) != EOF)
  {
    unsigned char u = c;
    write (file_descriptor, &amp;u, 1);
  }</pre>
</div>
<p><a name="index-casting-pointers-to-integers"></a></p>
<p>Avoid casting pointers to integers if you can. Such casts greatly reduce portability, and in most programs they are easy to avoid. In the cases where casting pointers to integers is essential—such as, a Lisp interpreter which stores type information as well as an address in one word—you’ll have to make explicit provisions to handle different word sizes. You will also need to make provision for systems in which the normal range of addresses you can get from <code>malloc</code> starts far away from zero.</p>
<hr />
<p><a name="System-Functions"></a></p>
<div>
<p>Next: <a href="http://www.gnu.org/prep/standards/standards.html#Internationalization" rel="next">Internationalization</a>, Previous: <a href="http://www.gnu.org/prep/standards/standards.html#CPU-Portability" rel="prev">CPU Portability</a>, Up: <a href="http://www.gnu.org/prep/standards/standards.html#Writing-C" rel="up">Writing C</a>   [<a title="Table of contents" href="http://www.gnu.org/prep/standards/standards.html#SEC_Contents" rel="contents">Contents</a>][<a title="Index" href="http://www.gnu.org/prep/standards/standards.html#Index" rel="index">Index</a>]</p>
</div>
<p><a name="Calling-System-Functions"></a></p>
<h3>5.7 Calling System Functions</h3>
<p><a name="index-C-library-functions_002c-and-portability"></a> <a name="index-POSIX-functions_002c-and-portability"></a> <a name="index-library-functions_002c-and-portability"></a> <a name="index-portability_002c-and-library-functions"></a></p>
<p>Historically, C implementations differed substantially, and many systems lacked a full implementation of ANSI/ISO C89. Nowadays, however, all practical systems have a C89 compiler and GNU C supports almost all of C99 and some of C11. Similarly, most systems implement POSIX.1-2001 libraries and tools, and many have POSIX.1-2008.</p>
<p>Hence, there is little reason to support old C or non-POSIX systems, and you may want to take advantage of standard C and POSIX to write clearer, more portable, or faster code. You should use standard interfaces where possible; but if GNU extensions make your program more maintainable, powerful, or otherwise better, don’t hesitate to use them. In any case, don’t make your own declaration of system functions; that’s a recipe for conflict.</p>
<p>Despite the standards, nearly every library function has some sort of portability issue on some system or another. Here are some examples:</p>
<dl>
<dt><code>open</code></dt>
<dd>Names with trailing <code>/</code>’s are mishandled on many platforms.</p>
</dd>
<dt><code>printf</code></dt>
<dd><code>long double</code> may be unimplemented; floating values Infinity and NaN are often mishandled; output for large precisions may be incorrect.</p>
</dd>
<dt><code>readlink</code></dt>
<dd>May return <code>int</code> instead of <code>ssize_t</code>.</p>
</dd>
<dt><code>scanf</code></dt>
<dd>On Windows, <code>errno</code> is not set on failure.</p>
</dd>
</dl>
<p><a name="index-Gnulib"></a></p>
<p><a href="http://www.gnu.org/software/gnulib/">Gnulib</a> is a big help in this regard. Gnulib provides implementations of standard interfaces on many of the systems that lack them, including portable implementations of enhanced GNU interfaces, thereby making their use portable, and of POSIX-1.2008 interfaces, some of which are missing even on up-to-date GNU systems.</p>
<p><a name="index-xmalloc_002c-in-Gnulib"></a> <a name="index-error-messages_002c-in-Gnulib"></a> <a name="index-data-structures_002c-in-Gnulib"></a></p>
<p>Gnulib also provides many useful non-standard interfaces; for example, C implementations of standard data structures (hash tables, binary trees), error-checking type-safe wrappers for memory allocation functions (<code>xmalloc</code>, <code>xrealloc</code>), and output of error messages.</p>
<p>Gnulib integrates with GNU Autoconf and Automake to remove much of the burden of writing portable code from the programmer: Gnulib makes your configure script automatically determine what features are missing and use the Gnulib code to supply the missing pieces.</p>
<p>The Gnulib and Autoconf manuals have extensive sections on portability: <a href="http://www.gnu.org/software/gnulib/manual/gnulib.html#Top">Introduction</a> in <cite>Gnulib</cite> and see <a href="http://www.gnu.org/software/autoconf/manual/autoconf.html#Portable-C-and-C_002b_002b">Portable C and C++</a> in <cite>Autoconf</cite>. Please consult them for many more details.</p>
<hr />
<p><a name="Internationalization"></a></p>
<div>
<p>Next: <a href="http://www.gnu.org/prep/standards/standards.html#Character-Set" rel="next">Character Set</a>, Previous: <a href="http://www.gnu.org/prep/standards/standards.html#System-Functions" rel="prev">System Functions</a>, Up: <a href="http://www.gnu.org/prep/standards/standards.html#Writing-C" rel="up">Writing C</a>   [<a title="Table of contents" href="http://www.gnu.org/prep/standards/standards.html#SEC_Contents" rel="contents">Contents</a>][<a title="Index" href="http://www.gnu.org/prep/standards/standards.html#Index" rel="index">Index</a>]</p>
</div>
<p><a name="Internationalization-1"></a></p>
<h3>5.8 Internationalization</h3>
<p><a name="index-internationalization"></a> <a name="index-gettext"></a></p>
<p>GNU has a library called GNU gettext that makes it easy to translate the messages in a program into various languages. You should use this library in every program. Use English for the messages as they appear in the program, and let gettext provide the way to translate them into other languages.</p>
<p>Using GNU gettext involves putting a call to the <code>gettext</code> macro around each string that might need translation—like this:</p>
<div>
<pre>printf (gettext ("Processing file '%s'..."), file);</pre>
</div>
<p>This permits GNU gettext to replace the string <code>"Processing file '%s'..."</code> with a translated version.</p>
<p>Once a program uses gettext, please make a point of writing calls to <code>gettext</code> when you add new strings that call for translation.</p>
<p>Using GNU gettext in a package involves specifying a <em>text domain name</em>for the package. The text domain name is used to separate the translations for this package from the translations for other packages. Normally, the text domain name should be the same as the name of the package—for example, ‘coreutils’ for the GNU core utilities.</p>
<p><a name="index-message-text_002c-and-internationalization"></a></p>
<p>To enable gettext to work well, avoid writing code that makes assumptions about the structure of words or sentences. When you want the precise text of a sentence to vary depending on the data, use two or more alternative string constants each containing a complete sentences, rather than inserting conditionalized words or phrases into a single sentence framework.</p>
<p>Here is an example of what not to do:</p>
<div>
<pre>printf ("%s is full", capacity &gt; 5000000 ? "disk" : "floppy disk");</pre>
</div>
<p>If you apply gettext to all strings, like this,</p>
<div>
<pre>printf (gettext ("%s is full"),
        capacity &gt; 5000000 ? gettext ("disk") : gettext ("floppy disk"));</pre>
</div>
<p>the translator will hardly know that &#8220;disk&#8221; and &#8220;floppy disk&#8221; are meant to be substituted in the other string. Worse, in some languages (like French) the construction will not work: the translation of the word &#8220;full&#8221; depends on the gender of the first part of the sentence; it happens to be not the same for &#8220;disk&#8221; as for &#8220;floppy disk&#8221;.</p>
<p>Complete sentences can be translated without problems:</p>
<div>
<pre>printf (capacity &gt; 5000000 ? gettext ("disk is full")
        : gettext ("floppy disk is full"));</pre>
</div>
<p>A similar problem appears at the level of sentence structure with this code:</p>
<div>
<pre>printf ("#  Implicit rule search has%s been done.\n",
        f-&gt;tried_implicit ? "" : " not");</pre>
</div>
<p>Adding <code>gettext</code> calls to this code cannot give correct results for all languages, because negation in some languages requires adding words at more than one place in the sentence. By contrast, adding <code>gettext</code> calls does the job straightforwardly if the code starts out like this:</p>
<div>
<pre>printf (f-&gt;tried_implicit
        ? "#  Implicit rule search has been done.\n",
        : "#  Implicit rule search has not been done.\n");</pre>
</div>
<p>Another example is this one:</p>
<div>
<pre>printf ("%d file%s processed", nfiles,
        nfiles != 1 ? "s" : "");</pre>
</div>
<p>The problem with this example is that it assumes that plurals are made by adding ‘s’. If you apply gettext to the format string, like this,</p>
<div>
<pre>printf (gettext ("%d file%s processed"), nfiles,
        nfiles != 1 ? "s" : "");</pre>
</div>
<p>the message can use different words, but it will still be forced to use ‘s’ for the plural. Here is a better way, with gettext being applied to the two strings independently:</p>
<div>
<pre>printf ((nfiles != 1 ? gettext ("%d files processed")
         : gettext ("%d file processed")),
        nfiles);</pre>
</div>
<p>But this still doesn’t work for languages like Polish, which has three plural forms: one for nfiles == 1, one for nfiles == 2, 3, 4, 22, 23, 24, &#8230; and one for the rest. The GNU <code>ngettext</code> function solves this problem:</p>
<div>
<pre>printf (ngettext ("%d files processed", "%d file processed", nfiles),
        nfiles);</pre>
</div>
<hr />
<p><a name="Character-Set"></a></p>
<div>
<p>Next: <a href="http://www.gnu.org/prep/standards/standards.html#Quote-Characters" rel="next">Quote Characters</a>, Previous: <a href="http://www.gnu.org/prep/standards/standards.html#Internationalization" rel="prev">Internationalization</a>, Up: <a href="http://www.gnu.org/prep/standards/standards.html#Writing-C" rel="up">Writing C</a>   [<a title="Table of contents" href="http://www.gnu.org/prep/standards/standards.html#SEC_Contents" rel="contents">Contents</a>][<a title="Index" href="http://www.gnu.org/prep/standards/standards.html#Index" rel="index">Index</a>]</p>
</div>
<p><a name="Character-Set-1"></a></p>
<h3>5.9 Character Set</h3>
<p><a name="index-character-set"></a> <a name="index-encodings"></a> <a name="index-ASCII-characters"></a> <a name="index-non_002dASCII-characters"></a></p>
<p>Sticking to the ASCII character set (plain text, 7-bit characters) is preferred in GNU source code comments, text documents, and other contexts, unless there is good reason to do something else because of the application domain. For example, if source code deals with the French Revolutionary calendar, it is OK if its literal strings contain accented characters in month names like “Floréal”. Also, it is OK (but not required) to use non-ASCII characters to represent proper names of contributors in change logs (see <a href="http://www.gnu.org/prep/standards/standards.html#Change-Logs">Change Logs</a>).</p>
<p>If you need to use non-ASCII characters, you should normally stick with one encoding, certainly within a single file. UTF-8 is likely to be the best choice.</p>
<hr />
<p><a name="Quote-Characters"></a></p>
<div>
<p>Next: <a href="http://www.gnu.org/prep/standards/standards.html#Mmap" rel="next">Mmap</a>, Previous: <a href="http://www.gnu.org/prep/standards/standards.html#Character-Set" rel="prev">Character Set</a>, Up: <a href="http://www.gnu.org/prep/standards/standards.html#Writing-C" rel="up">Writing C</a>   [<a title="Table of contents" href="http://www.gnu.org/prep/standards/standards.html#SEC_Contents" rel="contents">Contents</a>][<a title="Index" href="http://www.gnu.org/prep/standards/standards.html#Index" rel="index">Index</a>]</p>
</div>
<p><a name="Quote-Characters-1"></a></p>
<h3>5.10 Quote Characters</h3>
<p><a name="index-quote-characters"></a> <a name="index-locale_002dspecific-quote-characters"></a> <a name="index-left-quote"></a> <a name="index-right-quote"></a> <a name="index-opening-quote"></a> <a name="index-single-quote"></a> <a name="index-double-quote"></a> <a name="index-grave-accent"></a></p>
<p>In the C locale, the output of GNU programs should stick to plain ASCII for quotation characters in messages to users: preferably 0&#215;22 (‘&#8221;’) or 0&#215;27 (‘&#8217;’) for both opening and closing quotes. Although GNU programs traditionally used 0&#215;60 (‘`’) for opening and 0&#215;27 (‘&#8217;’) for closing quotes, nowadays quotes ‘`like this&#8217;’ are typically rendered asymmetrically, so quoting ‘&#8221;like this&#8221;’ or ‘&#8217;like this&#8217;’ typically looks better.</p>
<p>It is ok, but not required, for GNU programs to generate locale-specific quotes in non-C locales. For example:</p>
<div>
<pre>printf (gettext ("Processing file '%s'..."), file);</pre>
</div>
<p>Here, a French translation might cause <code>gettext</code> to return the string <code>"Traitement de fichier ‹ %s ›..."</code>, yielding quotes more appropriate for a French locale.</p>
<p>Sometimes a program may need to use opening and closing quotes directly. By convention, <code>gettext</code>translates the string ‘&#8221;`&#8221;’ to the opening quote and the string ‘&#8221;&#8216;&#8221;’ to the closing quote, and a program can use these translations. Generally, though, it is better to translate quote characters in the context of longer strings.</p>
<p>If the output of your program is ever likely to be parsed by another program, it is good to provide an option that makes this parsing reliable. For example, you could escape special characters using conventions from the C language or the Bourne shell. See for example the option&#8211;quoting-styleof GNU <code>ls</code>.</p>
<hr />
<p><a name="Mmap"></a></p>
<div>
<p>Previous: <a href="http://www.gnu.org/prep/standards/standards.html#Quote-Characters" rel="prev">Quote Characters</a>, Up: <a href="http://www.gnu.org/prep/standards/standards.html#Writing-C" rel="up">Writing C</a>   [<a title="Table of contents" href="http://www.gnu.org/prep/standards/standards.html#SEC_Contents" rel="contents">Contents</a>][<a title="Index" href="http://www.gnu.org/prep/standards/standards.html#Index" rel="index">Index</a>]</p>
</div>
<p><a name="Mmap-1"></a></p>
<h3>5.11 Mmap</h3>
<p><a name="index-mmap"></a></p>
<p>If you use <code>mmap</code> to read or write files, don’t assume it either works on all files or fails for all files. It may work on some files and fail on others.</p>
<p>The proper way to use <code>mmap</code> is to try it on the specific file for which you want to use it—and if <code>mmap</code> doesn’t work, fall back on doing the job in another way using <code>read</code> and <code>write</code>.</p>
<p>The reason this precaution is needed is that the GNU kernel (the HURD) provides a user-extensible file system, in which there can be many different kinds of “ordinary files”. Many of them support <code>mmap</code>, but some do not. It is important to make programs handle all these kinds of files.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.emblogic.com/blog/03/best-ways-to-implement-c-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>FACTS ABOUT BITWISE OPERATORS..</title>
		<link>https://www.emblogic.com/blog/03/facts-about-bitwise-operators/</link>
		<comments>https://www.emblogic.com/blog/03/facts-about-bitwise-operators/#comments</comments>
		<pubDate>Mon, 03 Mar 2014 17:43:40 +0000</pubDate>
		<dc:creator><![CDATA[gkarya1990]]></dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.emblogic.com/blog/?p=8862</guid>
		<description><![CDATA[Interesting Facts about Bitwise Operators in C In C, following 6 operators are bitwise operators (work at bit-level) &#38; (bitwise AND) Takes two numbers as operand and does AND on every bit of two numbers. The result of AND is &#8230; <a href="https://www.emblogic.com/blog/03/facts-about-bitwise-operators/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<div>
<h2>Interesting Facts about Bitwise Operators in C</h2>
</div>
<p>In C, following 6 operators are bitwise operators (work at bit-level)</p>
<p><strong>&amp; (bitwise AND)</strong> Takes two numbers as operand and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.</p>
<p><strong>| (bitwise OR)</strong> Takes two numbers as operand and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1.</p>
<p><strong>^ (bitwise XOR)</strong> Takes two numbers as operand and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.</p>
<p><strong>&lt;&lt; (left shift)</strong> Takes two numbers, left shifts the bits of first operand, the second operand decides the number of places to shift.</p>
<p><strong>&gt;&gt; (right shift)</strong> Takes two numbers, right shifts the bits of first operand, the second operand decides the number of places to shift.</p>
<p><strong>~ (bitwise NOT)</strong> Takes one number and inverts all bits of it</p>
<p>Following is example C program.</p>
<div>
<div>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div>
<div><code>/* C Program to demonstrate use of bitwise operators */</code></div>
<div><code>#include&lt;stdio.h&gt;</code></div>
<div><code>int</code> <code>main()</code></div>
<div><code>{</code></div>
<div><code>    </code><code>unsigned </code><code>char</code> <code>a = 5, b = 9; </code><code>// a = 4(00000101), b = 8(00001001)</code></div>
<div><code>    </code><code>printf</code><code>(</code><code>"a = %d, b = %d\n"</code><code>, a, b);</code></div>
<div><code>    </code><code>printf</code><code>(</code><code>"a&amp;b = %d\n"</code><code>, a&amp;b); </code><code>// The result is 00000001</code></div>
<div><code>    </code><code>printf</code><code>(</code><code>"a|b = %d\n"</code><code>, a|b);  </code><code>// The result is 00001101</code></div>
<div><code>    </code><code>printf</code><code>(</code><code>"a^b = %d\n"</code><code>, a^b); </code><code>// The result is 00001100</code></div>
<div><code>    </code><code>printf</code><code>(</code><code>"~a = %d\n"</code><code>, a = ~a);   </code><code>// The result is 11111010</code></div>
<div><code>    </code><code>printf</code><code>(</code><code>"b&lt;&lt;1 = %d\n"</code><code>, b&lt;&lt;1);  </code><code>// The result is 00010010 </code></div>
<div><code>    </code><code>printf</code><code>(</code><code>"b&gt;&gt;1 = %d\n"</code><code>, b&gt;&gt;1);  </code><code>// The result is 00000100 </code></div>
<div><code>    </code><code>return</code> <code>0;</code></div>
<div><code>}</code></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>Output:</p>
<pre>a = 5, b = 9
a&amp;b = 1
a|b = 13
a^b = 12
~a = 250
b&lt;&lt;1 = 18
b&gt;&gt;1 = 4</pre>
<p>Following are interesting facts about bitwise operators.</p>
<p><strong>1) The left shift and right shift operators should not be used for negative numbers</strong> The result of &lt;&lt; and &gt;&gt; is undefined behabiour if any of the operands is a negative number. For example results of both -1 &lt;&lt; 1 and 1 &lt;&lt; -1 is undefined. Also, if the number is shifted more than the size of integer, the behaviour is undefined. For example, 1 &lt;&lt; 33 is undefined if integers are stored using 32 bits. See <a href="https://www.securecoding.cert.org/confluence/display/seccode/INT34-C.+Do+not+shift+a+negative+number+of+bits+or+more+bits+than+exist+in+the+operand" target="_blank">this</a> for more details.</p>
<p><strong>2) The bitwise XOR operator is the most useful operator from technical interview perspective.</strong> It is used in many problems. A simple example could be “Given a set of numbers where all elements occur even number of times except one number, find the odd occuring number” This problem can be efficiently solved by just doing XOR of all numbers.</p>
<div>
<div>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div>
<div><code>// Function to return the only odd occurring element</code></div>
<div><code>int</code> <code>findOdd(</code><code>int</code> <code>arr[], </code><code>int</code> <code>n) {</code></div>
<div><code>   </code><code>int</code> <code>res = 0, i;</code></div>
<div><code>   </code><code>for</code> <code>(i = 0; i &lt; n; i++)</code></div>
<div><code>     </code><code>res ^= arr[i];</code></div>
<div><code>   </code><code>return</code> <code>res;</code></div>
<div><code>}</code></div>
<div></div>
<div><code>int</code> <code>main(</code><code>void</code><code>) {</code></div>
<div><code>   </code><code>int</code> <code>arr[] = {12, 12, 14, 90, 14, 14, 14};</code></div>
<div><code>   </code><code>int</code> <code>n = </code><code>sizeof</code><code>(arr)/</code><code>sizeof</code><code>(arr[0]);</code></div>
<div><code>   </code><code>printf</code> <code>(</code><code>"The odd occurring element is %d "</code><code>, findOdd(arr, n));</code></div>
<div><code>   </code><code>return</code> <code>0;</code></div>
<div><code>}</code></div>
<div><code>// Output: The odd occurring element is 90</code></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>The following are many other interesting problems which can be used using XOR operator.<br />
<a href="http://www.geeksforgeeks.org/find-the-missing-number/" target="_blank">Find the Missing Number</a>, <a href="http://www.geeksforgeeks.org/swap-two-numbers-without-using-temporary-variable/" target="_blank">swap two numbers without using a temporary variable</a>, <a href="http://www.geeksforgeeks.org/xor-linked-list-a-memory-efficient-doubly-linked-list-set-1/" target="_blank">A Memory Efficient Doubly Linked List</a>, and <a href="http://www.geeksforgeeks.org/find-two-non-repeating-elements-in-an-array-of-repeating-elements/" target="_blank">Find the two non-repeating elements</a>. There are many more (See <a href="http://www.geeksforgeeks.org/find-the-two-numbers-with-odd-occurences-in-an-unsorted-array/" target="_blank">this</a>, <a href="http://www.geeksforgeeks.org/add-two-numbers-without-using-arithmetic-operators/" target="_blank">this</a>, <a href="http://www.geeksforgeeks.org/swap-bits-in-a-given-number/" target="_blank">this</a>, <a href="http://www.geeksforgeeks.org/count-number-of-bits-to-be-flipped-to-convert-a-to-b/" target="_blank">this</a>, <a href="http://www.geeksforgeeks.org/find-the-element-that-appears-once/" target="_blank">this</a> and <a href="http://www.geeksforgeeks.org/detect-if-two-integers-have-opposite-signs/" target="_blank">this</a>)</p>
<p><strong>3) The bitwise operators should not be used in-place of logical operators.</strong><br />
The result of logical operators (&amp;&amp;, || and !) is either 0 or 1, but bitwise operators return an integer value. Also, the logical operators consider any non-zero operand as 1. For example consider the following program, the results of &amp; and &amp;&amp; are different for same operands.</p>
<div>
<div>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div>
<div><code>int</code> <code>main()</code></div>
<div><code>{</code></div>
<div><code>   </code><code>int</code> <code>x = 2, y = 5;</code></div>
<div><code>   </code><code>(x &amp; y)? </code><code>printf</code><code>(</code><code>"True "</code><code>) : </code><code>printf</code><code>(</code><code>"False "</code><code>);</code></div>
<div><code>   </code><code>(x &amp;&amp; y)? </code><code>printf</code><code>(</code><code>"True "</code><code>) : </code><code>printf</code><code>(</code><code>"False "</code><code>);</code></div>
<div><code>   </code><code>return</code> <code>0;</code></div>
<div><code>}</code></div>
<div><code>// Output: False True</code></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<p><strong>4) The left-shift and right-shift operators are equivalent to multiplication and division by 2 respectively.</strong><br />
As mentioned in point 1, it works only if numbers are positive.</p>
<div>
<div>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div>
<div><code>int</code> <code>main()</code></div>
<div><code>{</code></div>
<div><code>   </code><code>int</code> <code>x = 19;</code></div>
<div><code>   </code><code>printf</code> <code>(</code><code>"x &lt;&lt; 1 = %d\n"</code><code>, x &lt;&lt; 1);</code></div>
<div><code>   </code><code>printf</code> <code>(</code><code>"x &gt;&gt; 1 = %d\n"</code><code>, x &gt;&gt; 1);</code></div>
<div><code>   </code><code>return</code> <code>0;</code></div>
<div><code>}</code></div>
<div><code>// Output: 38 9</code></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<p><strong>5) The &amp; operator can be used to quickly check if a number is odd or even</strong><br />
The value of expression (x &amp; 1) would be non-zero only if x is odd, otherwise the value would be zero.</p>
<div>
<div>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div>
<div><code>int</code> <code>main()</code></div>
<div><code>{</code></div>
<div><code>   </code><code>int</code> <code>x = 19;</code></div>
<div><code>   </code><code>(x &amp; 1)? </code><code>printf</code><code>(</code><code>"Odd"</code><code>): </code><code>printf</code><code>(</code><code>"Even"</code><code>);</code></div>
<div><code>   </code><code>return</code> <code>0;</code></div>
<div><code>}</code></div>
<div><code>// Output: Odd</code></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<p><strong>6) The ~ operator should be used carefully</strong><br />
The result of ~ operator on a small number can be a big number if result is stored in a unsigned variable. And result may be negative number if result is stored in signed variable (assuming that the negative numbers are stored in 2?s complement form where leftmost bit is the sign bit)</p>
<div>
<div><code>// Note that the output of following program is compiler dependent</code></div>
<div><code>int</code> <code>main()</code></div>
<div><code>{</code></div>
<div><code>   </code><code>unsigned </code><code>int</code> <code>x = 1;</code></div>
<div><code>   </code><code>printf</code><code>(</code><code>"Signed Result %d \n"</code><code>, ~x);</code></div>
<div><code>   </code><code>printf</code><code>(</code><code>"Unsigned Result %ud \n"</code><code>, ~x);</code></div>
<div><code>   </code><code>return</code> <code>0;</code></div>
<div><code>}</code></div>
<div><code>/* Output: </code></div>
<div><code>Signed Result -2 </code></div>
<div><code>Unsigned Result 4294967294d */</code></div>
</div>
]]></content:encoded>
			<wfw:commentRss>https://www.emblogic.com/blog/03/facts-about-bitwise-operators/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
