<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Casually explained]]></title><description><![CDATA[Fullstack developer]]></description><link>https://kshitijcodes.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 13 Nov 2026 15:41:46 GMT</lastBuildDate><atom:link href="https://kshitijcodes.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[XSS Vulnerabilities in Frontend System Design: A Practical Guide for Frontend Engineers]]></title><description><![CDATA[Learn about XSS vulnerabilities, their impact, and practical prevention strategies for frontend engineers to secure React and Next.js applications]]></description><link>https://kshitijcodes.hashnode.dev/xss-vulnerabilities-in-frontend-system-design-a-practical-guide-for-frontend-engineers</link><guid isPermaLink="true">https://kshitijcodes.hashnode.dev/xss-vulnerabilities-in-frontend-system-design-a-practical-guide-for-frontend-engineers</guid><category><![CDATA[Frontend Development]]></category><category><![CDATA[System Design]]></category><category><![CDATA[webdev]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Next.js]]></category><category><![CDATA[Web Security]]></category><category><![CDATA[React]]></category><category><![CDATA[frontend]]></category><category><![CDATA[cross site scripting]]></category><dc:creator><![CDATA[Kshitij Sharma]]></dc:creator><pubDate>Sun, 08 Jun 2025 07:15:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1749366569405/55f7c5b2-dfce-4072-b885-99d728985ef2.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Picture this: You've just shipped a beautiful React dashboard for your SaaS product. Users are loving the new comment system, the rich text editor is working perfectly, and your PM is happy. Then, one morning, you get a Slack message that makes your coffee go cold: "We've detected malicious scripts running on user profiles. All hands on deck."</p>
<p>Welcome to the world of Cross-Site Scripting (XSS) vulnerabilities—one of the most common and dangerous security issues in frontend development.</p>
<h2 id="heading-why-xss-should-keep-you-up-at-night">Why XSS Should Keep You Up at Night</h2>
<p>XSS isn't just a theoretical security concern that happens to "other people's apps." It's a real threat that can:</p>
<ul>
<li><p>Steal user session tokens and authentication cookies</p>
</li>
<li><p>Redirect users to malicious websites</p>
</li>
<li><p>Modify the DOM to create fake login forms</p>
</li>
<li><p>Access sensitive user data and send it to attackers</p>
</li>
<li><p>Turn your application into a launching pad for attacks on other users</p>
</li>
</ul>
<p>The scary part? Most XSS vulnerabilities in modern frontend applications don't come from obvious places like <code>eval()</code> or <code>innerHTML</code>. They hide in seemingly innocent features like user profiles, comment systems, notification displays, and rich content editors.</p>
<p>As a frontend engineer, you're the first line of defense. Understanding XSS isn't just about passing interviews—it's about building applications that users can actually trust.</p>
<h2 id="heading-the-three-faces-of-xss">The Three Faces of XSS</h2>
<p>Let's break down the three main types of XSS vulnerabilities you'll encounter in real-world frontend applications.</p>
<h3 id="heading-1-stored-xss-the-persistent-threat">1. Stored XSS: The Persistent Threat</h3>
<p>Stored XSS is like a time bomb. The malicious script gets saved to your database and executes every time someone views the infected content.</p>
<p>Here's how it typically happens in a React application:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// UserProfile.js - VULNERABLE CODE</span>
<span class="hljs-keyword">import</span> { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UserProfile</span>(<span class="hljs-params">{ userId }</span>) </span>{
  <span class="hljs-keyword">const</span> [profile, setProfile] = useState(<span class="hljs-literal">null</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    fetch(<span class="hljs-string">`/api/users/<span class="hljs-subst">${userId}</span>`</span>)
      .then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> res.json())
      .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> setProfile(data));
  }, [userId]);

  <span class="hljs-keyword">if</span> (!profile) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"profile"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>{profile.name}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"bio"</span>&gt;</span>
        {/* DANGER: This will execute any script tags in the bio */}
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">dangerouslySetInnerHTML</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">__html:</span> <span class="hljs-attr">profile.bio</span> }} /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p><strong>How the attack works:</strong></p>
<ol>
<li><p>Attacker creates a profile with bio: <code>&lt;script&gt;fetch('/api/steal-data', {method: 'POST', body: document.cookie})&lt;/script&gt;</code></p>
</li>
<li><p>This gets stored in your database</p>
</li>
<li><p>Every time someone views this profile, the script executes</p>
</li>
<li><p>The attacker now has access to every visitor's session cookies</p>
</li>
</ol>
<p><strong>The fix:</strong></p>
<pre><code class="lang-jsx"><span class="hljs-comment">// UserProfile.js - SECURE VERSION</span>
<span class="hljs-keyword">import</span> { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> DOMPurify <span class="hljs-keyword">from</span> <span class="hljs-string">'dompurify'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UserProfile</span>(<span class="hljs-params">{ userId }</span>) </span>{
  <span class="hljs-keyword">const</span> [profile, setProfile] = useState(<span class="hljs-literal">null</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    fetch(<span class="hljs-string">`/api/users/<span class="hljs-subst">${userId}</span>`</span>)
      .then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> res.json())
      .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> setProfile(data));
  }, [userId]);

  <span class="hljs-keyword">if</span> (!profile) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;

  <span class="hljs-comment">// Sanitize HTML before rendering</span>
  <span class="hljs-keyword">const</span> sanitizedBio = DOMPurify.sanitize(profile.bio, {
    <span class="hljs-attr">ALLOWED_TAGS</span>: [<span class="hljs-string">'p'</span>, <span class="hljs-string">'br'</span>, <span class="hljs-string">'strong'</span>, <span class="hljs-string">'em'</span>, <span class="hljs-string">'ul'</span>, <span class="hljs-string">'ol'</span>, <span class="hljs-string">'li'</span>],
    <span class="hljs-attr">ALLOWED_ATTR</span>: []
  });

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"profile"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>{profile.name}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"bio"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">dangerouslySetInnerHTML</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">__html:</span> <span class="hljs-attr">sanitizedBio</span> }} /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<h3 id="heading-2-reflected-xss-the-mirror-attack">2. Reflected XSS: The Mirror Attack</h3>
<p>Reflected XSS happens when user input is immediately reflected back in the response without proper sanitization. This is common in search results, error messages, and URL parameters.</p>
<p>Here's a vulnerable Next.js search page:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// pages/search.js - VULNERABLE CODE</span>
<span class="hljs-keyword">import</span> { useRouter } <span class="hljs-keyword">from</span> <span class="hljs-string">'next/router'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">SearchPage</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> router = useRouter();
  <span class="hljs-keyword">const</span> { q } = router.query;

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Search Results<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      {q &amp;&amp; (
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
          {/* DANGER: URL parameter directly rendered */}
          You searched for: <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">dangerouslySetInnerHTML</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">__html:</span> <span class="hljs-attr">q</span> }} /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      )}
      {/* Search results would go here */}
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p><strong>How the attack works:</strong></p>
<ol>
<li><p>Attacker crafts a malicious URL: <a target="_blank" href="https://yourapp.com/search?q=&lt;script&gt;alert\('XSS'\)&lt;/script&gt;"><code>https://yourapp.com/search?q=&lt;script&gt;alert('XSS')&lt;/script&gt;</code></a></p>
</li>
<li><p>They trick users into clicking this link (via email, social media, etc.)</p>
</li>
<li><p>When users visit the link, the script executes immediately</p>
</li>
</ol>
<p><strong>The fix:</strong></p>
<pre><code class="lang-jsx"><span class="hljs-comment">// pages/search.js - SECURE VERSION</span>
<span class="hljs-keyword">import</span> { useRouter } <span class="hljs-keyword">from</span> <span class="hljs-string">'next/router'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">SearchPage</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> router = useRouter();
  <span class="hljs-keyword">const</span> { q } = router.query;

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Search Results<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      {q &amp;&amp; (
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
          {/* React automatically escapes this content */}
          You searched for: <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>{q}<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      )}
      {/* Search results would go here */}
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>The key insight here: React's default behavior is to escape content, which protects you. The vulnerability only appears when you deliberately bypass this protection with <code>dangerouslySetInnerHTML</code>.</p>
<h3 id="heading-3-dom-based-xss-the-client-side-trap">3. DOM-based XSS: The Client-Side Trap</h3>
<p>DOM-based XSS happens entirely in the browser, without the server being involved. The malicious payload is processed by client-side JavaScript.</p>
<p>Here's a common pattern in React apps that handle URL fragments:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// components/WelcomeMessage.js - VULNERABLE CODE</span>
<span class="hljs-keyword">import</span> { useEffect, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">WelcomeMessage</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [message, setMessage] = useState(<span class="hljs-string">''</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// Getting user name from URL fragment</span>
    <span class="hljs-keyword">const</span> hash = <span class="hljs-built_in">window</span>.location.hash;
    <span class="hljs-keyword">if</span> (hash.startsWith(<span class="hljs-string">'#welcome='</span>)) {
      <span class="hljs-keyword">const</span> userName = hash.substring(<span class="hljs-number">9</span>); <span class="hljs-comment">// Remove '#welcome='</span>
      <span class="hljs-comment">// DANGER: Directly inserting URL content into DOM</span>
      <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'welcome'</span>).innerHTML = <span class="hljs-string">`Welcome back, <span class="hljs-subst">${userName}</span>!`</span>;
    }
  }, []);

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"welcome"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
}
</code></pre>
<p><strong>How the attack works:</strong></p>
<ol>
<li><p>Attacker creates a malicious URL: <a target="_blank" href="https://yourapp.com/#welcome=&lt;img"><code>https://yourapp.com/#welcome=&lt;img</code></a> <code>src=x onerror=alert('XSS')&gt;</code></p>
</li>
<li><p>The fragment is processed by client-side JavaScript</p>
</li>
<li><p>The malicious code executes without any server interaction</p>
</li>
</ol>
<p><strong>The fix:</strong></p>
<pre><code class="lang-jsx"><span class="hljs-comment">// components/WelcomeMessage.js - SECURE VERSION</span>
<span class="hljs-keyword">import</span> { useEffect, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">WelcomeMessage</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [userName, setUserName] = useState(<span class="hljs-string">''</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> hash = <span class="hljs-built_in">window</span>.location.hash;
    <span class="hljs-keyword">if</span> (hash.startsWith(<span class="hljs-string">'#welcome='</span>)) {
      <span class="hljs-keyword">const</span> name = hash.substring(<span class="hljs-number">9</span>);
      <span class="hljs-comment">// Let React handle the escaping</span>
      setUserName(<span class="hljs-built_in">decodeURIComponent</span>(name));
    }
  }, []);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      {userName &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Welcome back, {userName}!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<h2 id="heading-xss-in-unexpected-places">XSS in Unexpected Places</h2>
<p>Now that you understand the basics, let's explore where XSS vulnerabilities love to hide in modern SaaS applications.</p>
<h3 id="heading-content-management-systems">Content Management Systems</h3>
<p>Many SaaS apps have marketing pages managed through a CMS. Here's a vulnerable pattern:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// components/MarketingBanner.js - VULNERABLE CODE</span>
<span class="hljs-keyword">import</span> { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MarketingBanner</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [bannerContent, setBannerContent] = useState(<span class="hljs-string">''</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    fetch(<span class="hljs-string">'/api/cms/banner'</span>)
      .then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> res.json())
      .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> setBannerContent(data.html));
  }, []);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> 
      <span class="hljs-attr">className</span>=<span class="hljs-string">"marketing-banner"</span>
      <span class="hljs-attr">dangerouslySetInnerHTML</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">__html:</span> <span class="hljs-attr">bannerContent</span> }}
    /&gt;</span></span>
  );
}
</code></pre>
<p>The problem: If your CMS doesn't properly sanitize content, or if an attacker gains access to your CMS, they can inject malicious scripts that will run on every page.</p>
<h3 id="heading-markdown-rendering">Markdown Rendering</h3>
<p>Rich text editors and markdown processors are common XSS entry points:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// components/BlogPost.js - VULNERABLE CODE</span>
<span class="hljs-keyword">import</span> { marked } <span class="hljs-keyword">from</span> <span class="hljs-string">'marked'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">BlogPost</span>(<span class="hljs-params">{ content }</span>) </span>{
  <span class="hljs-keyword">const</span> htmlContent = marked(content);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">article</span> 
      <span class="hljs-attr">dangerouslySetInnerHTML</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">__html:</span> <span class="hljs-attr">htmlContent</span> }}
    /&gt;</span></span>
  );
}
</code></pre>
<p><strong>The secure approach:</strong></p>
<pre><code class="lang-jsx"><span class="hljs-comment">// components/BlogPost.js - SECURE VERSION</span>
<span class="hljs-keyword">import</span> { marked } <span class="hljs-keyword">from</span> <span class="hljs-string">'marked'</span>;
<span class="hljs-keyword">import</span> DOMPurify <span class="hljs-keyword">from</span> <span class="hljs-string">'dompurify'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">BlogPost</span>(<span class="hljs-params">{ content }</span>) </span>{
  <span class="hljs-keyword">const</span> htmlContent = marked(content);
  <span class="hljs-keyword">const</span> sanitizedContent = DOMPurify.sanitize(htmlContent, {
    <span class="hljs-attr">ALLOWED_TAGS</span>: [<span class="hljs-string">'p'</span>, <span class="hljs-string">'br'</span>, <span class="hljs-string">'strong'</span>, <span class="hljs-string">'em'</span>, <span class="hljs-string">'h1'</span>, <span class="hljs-string">'h2'</span>, <span class="hljs-string">'h3'</span>, <span class="hljs-string">'ul'</span>, <span class="hljs-string">'ol'</span>, <span class="hljs-string">'li'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'code'</span>, <span class="hljs-string">'pre'</span>],
    <span class="hljs-attr">ALLOWED_ATTR</span>: [<span class="hljs-string">'href'</span>, <span class="hljs-string">'title'</span>],
    <span class="hljs-attr">ALLOWED_SCHEMES</span>: [<span class="hljs-string">'http'</span>, <span class="hljs-string">'https'</span>, <span class="hljs-string">'mailto'</span>]
  });

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">article</span> 
      <span class="hljs-attr">dangerouslySetInnerHTML</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">__html:</span> <span class="hljs-attr">sanitizedContent</span> }}
    /&gt;</span></span>
  );
}
</code></pre>
<h3 id="heading-notifications-and-toasts">Notifications and Toasts</h3>
<p>Notification systems often display user-generated content, making them prime XSS targets:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// components/NotificationToast.js - VULNERABLE CODE</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">NotificationToast</span>(<span class="hljs-params">{ notification }</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"toast"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> 
        <span class="hljs-attr">className</span>=<span class="hljs-string">"toast-message"</span>
        <span class="hljs-attr">dangerouslySetInnerHTML</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">__html:</span> <span class="hljs-attr">notification.message</span> }}
      /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p><strong>The secure version:</strong></p>
<pre><code class="lang-jsx"><span class="hljs-comment">// components/NotificationToast.js - SECURE VERSION</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">NotificationToast</span>(<span class="hljs-params">{ notification }</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"toast"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"toast-message"</span>&gt;</span>
        {notification.message}
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<h2 id="heading-safely-rendering-user-generated-content">Safely Rendering User-Generated Content</h2>
<p>Let's dive deep into how to handle user-generated content (UGC) securely in React and Next.js applications.</p>
<h3 id="heading-setting-up-dompurify">Setting Up DOMPurify</h3>
<p>First, install and configure DOMPurify:</p>
<pre><code class="lang-bash">npm install dompurify
npm install @types/dompurify  <span class="hljs-comment"># If using TypeScript</span>
</code></pre>
<p>Create a utility function for consistent sanitization:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// utils/sanitize.js</span>
<span class="hljs-keyword">import</span> DOMPurify <span class="hljs-keyword">from</span> <span class="hljs-string">'dompurify'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> sanitizeHtml = <span class="hljs-function">(<span class="hljs-params">dirty, options = {}</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> defaultOptions = {
    <span class="hljs-attr">ALLOWED_TAGS</span>: [<span class="hljs-string">'p'</span>, <span class="hljs-string">'br'</span>, <span class="hljs-string">'strong'</span>, <span class="hljs-string">'em'</span>, <span class="hljs-string">'ul'</span>, <span class="hljs-string">'ol'</span>, <span class="hljs-string">'li'</span>, <span class="hljs-string">'a'</span>],
    <span class="hljs-attr">ALLOWED_ATTR</span>: [<span class="hljs-string">'href'</span>, <span class="hljs-string">'title'</span>, <span class="hljs-string">'target'</span>],
    <span class="hljs-attr">ALLOWED_SCHEMES</span>: [<span class="hljs-string">'http'</span>, <span class="hljs-string">'https'</span>, <span class="hljs-string">'mailto'</span>],
    <span class="hljs-attr">FORBID_TAGS</span>: [<span class="hljs-string">'script'</span>, <span class="hljs-string">'object'</span>, <span class="hljs-string">'embed'</span>, <span class="hljs-string">'base'</span>, <span class="hljs-string">'link'</span>],
    <span class="hljs-attr">FORBID_ATTR</span>: [<span class="hljs-string">'style'</span>, <span class="hljs-string">'onerror'</span>, <span class="hljs-string">'onload'</span>, <span class="hljs-string">'onclick'</span>]
  };

  <span class="hljs-keyword">const</span> mergedOptions = { ...defaultOptions, ...options };
  <span class="hljs-keyword">return</span> DOMPurify.sanitize(dirty, mergedOptions);
};

<span class="hljs-comment">// For different content types</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> sanitizeMarkdown = <span class="hljs-function">(<span class="hljs-params">dirty</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> sanitizeHtml(dirty, {
    <span class="hljs-attr">ALLOWED_TAGS</span>: [<span class="hljs-string">'p'</span>, <span class="hljs-string">'br'</span>, <span class="hljs-string">'strong'</span>, <span class="hljs-string">'em'</span>, <span class="hljs-string">'h1'</span>, <span class="hljs-string">'h2'</span>, <span class="hljs-string">'h3'</span>, <span class="hljs-string">'h4'</span>, <span class="hljs-string">'h5'</span>, <span class="hljs-string">'h6'</span>, 
                   <span class="hljs-string">'ul'</span>, <span class="hljs-string">'ol'</span>, <span class="hljs-string">'li'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'code'</span>, <span class="hljs-string">'pre'</span>, <span class="hljs-string">'blockquote'</span>],
    <span class="hljs-attr">ALLOWED_ATTR</span>: [<span class="hljs-string">'href'</span>, <span class="hljs-string">'title'</span>]
  });
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> sanitizeBasicText = <span class="hljs-function">(<span class="hljs-params">dirty</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> sanitizeHtml(dirty, {
    <span class="hljs-attr">ALLOWED_TAGS</span>: [<span class="hljs-string">'p'</span>, <span class="hljs-string">'br'</span>, <span class="hljs-string">'strong'</span>, <span class="hljs-string">'em'</span>],
    <span class="hljs-attr">ALLOWED_ATTR</span>: []
  });
};
</code></pre>
<h3 id="heading-creating-a-safe-html-component">Creating a Safe HTML Component</h3>
<p>Build a reusable component for rendering sanitized HTML:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// components/SafeHtml.js</span>
<span class="hljs-keyword">import</span> { sanitizeHtml } <span class="hljs-keyword">from</span> <span class="hljs-string">'../utils/sanitize'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">SafeHtml</span>(<span class="hljs-params">{ html, className = <span class="hljs-string">''</span>, sanitizeOptions = {} }</span>) </span>{
  <span class="hljs-keyword">const</span> cleanHtml = sanitizeHtml(html, sanitizeOptions);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> 
      <span class="hljs-attr">className</span>=<span class="hljs-string">{className}</span>
      <span class="hljs-attr">dangerouslySetInnerHTML</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">__html:</span> <span class="hljs-attr">cleanHtml</span> }}
    /&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> SafeHtml;
</code></pre>
<h3 id="heading-usage-examples">Usage Examples</h3>
<pre><code class="lang-jsx"><span class="hljs-comment">// components/UserComment.js</span>
<span class="hljs-keyword">import</span> SafeHtml <span class="hljs-keyword">from</span> <span class="hljs-string">'./SafeHtml'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UserComment</span>(<span class="hljs-params">{ comment }</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"comment"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"comment-author"</span>&gt;</span>{comment.author}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">SafeHtml</span> 
        <span class="hljs-attr">html</span>=<span class="hljs-string">{comment.content}</span>
        <span class="hljs-attr">className</span>=<span class="hljs-string">"comment-content"</span>
        <span class="hljs-attr">sanitizeOptions</span>=<span class="hljs-string">{{</span>
          <span class="hljs-attr">ALLOWED_TAGS:</span> ['<span class="hljs-attr">p</span>', '<span class="hljs-attr">br</span>', '<span class="hljs-attr">strong</span>', '<span class="hljs-attr">em</span>', '<span class="hljs-attr">a</span>'],
          <span class="hljs-attr">ALLOWED_ATTR:</span> ['<span class="hljs-attr">href</span>']
        }}
      /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<h2 id="heading-security-best-practices-for-frontend-teams">Security Best Practices for Frontend Teams</h2>
<h3 id="heading-1-avoid-dangerouslysetinnerhtml-when-possible">1. Avoid <code>dangerouslySetInnerHTML</code> When Possible</h3>
<p>The best defense against XSS is to avoid rendering raw HTML altogether. React's default escaping behavior protects you:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// GOOD: React automatically escapes this</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UserName</span>(<span class="hljs-params">{ name }</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>{name}<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span></span>; <span class="hljs-comment">// Safe even if name contains &lt;script&gt;</span>
}

<span class="hljs-comment">// RISKY: Only use when absolutely necessary</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">RichContent</span>(<span class="hljs-params">{ html }</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">dangerouslySetInnerHTML</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">__html:</span> <span class="hljs-attr">sanitizeHtml</span>(<span class="hljs-attr">html</span>) }} /&gt;</span></span>;
}
</code></pre>
<h3 id="heading-2-implement-content-security-policy-csp">2. Implement Content Security Policy (CSP)</h3>
<p>Configure CSP headers in your Next.js application:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// next.config.js</span>
<span class="hljs-keyword">const</span> nextConfig = {
  <span class="hljs-keyword">async</span> headers() {
    <span class="hljs-keyword">return</span> [
      {
        <span class="hljs-attr">source</span>: <span class="hljs-string">'/(.*)'</span>,
        <span class="hljs-attr">headers</span>: [
          {
            <span class="hljs-attr">key</span>: <span class="hljs-string">'Content-Security-Policy'</span>,
            <span class="hljs-attr">value</span>: [
              <span class="hljs-string">"default-src 'self'"</span>,
              <span class="hljs-string">"script-src 'self' 'unsafe-inline'"</span>, <span class="hljs-comment">// Be more restrictive in production</span>
              <span class="hljs-string">"style-src 'self' 'unsafe-inline'"</span>,
              <span class="hljs-string">"img-src 'self' data: https:"</span>,
              <span class="hljs-string">"font-src 'self'"</span>,
              <span class="hljs-string">"connect-src 'self'"</span>,
              <span class="hljs-string">"frame-ancestors 'none'"</span>
            ].join(<span class="hljs-string">'; '</span>)
          }
        ]
      }
    ];
  }
};

<span class="hljs-built_in">module</span>.exports = nextConfig;
</code></pre>
<p>For production, create a more restrictive CSP:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// production CSP</span>
<span class="hljs-keyword">const</span> productionCSP = [
  <span class="hljs-string">"default-src 'self'"</span>,
  <span class="hljs-string">"script-src 'self'"</span>, <span class="hljs-comment">// Remove 'unsafe-inline'</span>
  <span class="hljs-string">"style-src 'self'"</span>,
  <span class="hljs-string">"img-src 'self' data: https:"</span>,
  <span class="hljs-string">"font-src 'self'"</span>,
  <span class="hljs-string">"connect-src 'self' https://api.yourservice.com"</span>,
  <span class="hljs-string">"frame-ancestors 'none'"</span>,
  <span class="hljs-string">"base-uri 'self'"</span>,
  <span class="hljs-string">"form-action 'self'"</span>
].join(<span class="hljs-string">'; '</span>);
</code></pre>
<h3 id="heading-3-input-validation-strategies">3. Input Validation Strategies</h3>
<p>Validate user input both on the client and server side:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// utils/validation.js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> validateUserInput = <span class="hljs-function">(<span class="hljs-params">input, type = <span class="hljs-string">'text'</span></span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> validators = {
    <span class="hljs-attr">text</span>: <span class="hljs-function">(<span class="hljs-params">str</span>) =&gt;</span> <span class="hljs-keyword">typeof</span> str === <span class="hljs-string">'string'</span> &amp;&amp; str.length &lt;= <span class="hljs-number">1000</span>,
    <span class="hljs-attr">email</span>: <span class="hljs-function">(<span class="hljs-params">str</span>) =&gt;</span> <span class="hljs-regexp">/^[^\s@]+@[^\s@]+\.[^\s@]+$/</span>.test(str),
    <span class="hljs-attr">url</span>: <span class="hljs-function">(<span class="hljs-params">str</span>) =&gt;</span> {
      <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> url = <span class="hljs-keyword">new</span> URL(str);
        <span class="hljs-keyword">return</span> [<span class="hljs-string">'http:'</span>, <span class="hljs-string">'https:'</span>].includes(url.protocol);
      } <span class="hljs-keyword">catch</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
      }
    }
  };

  <span class="hljs-keyword">return</span> validators[type] ? validators[type](input) : <span class="hljs-literal">false</span>;
};

<span class="hljs-comment">// In your component</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CommentForm</span>(<span class="hljs-params">{ onSubmit }</span>) </span>{
  <span class="hljs-keyword">const</span> [comment, setComment] = useState(<span class="hljs-string">''</span>);
  <span class="hljs-keyword">const</span> [error, setError] = useState(<span class="hljs-string">''</span>);

  <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    e.preventDefault();

    <span class="hljs-keyword">if</span> (!validateUserInput(comment, <span class="hljs-string">'text'</span>)) {
      setError(<span class="hljs-string">'Invalid comment content'</span>);
      <span class="hljs-keyword">return</span>;
    }

    onSubmit(comment);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">textarea</span> 
        <span class="hljs-attr">value</span>=<span class="hljs-string">{comment}</span>
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setComment(e.target.value)}
        maxLength={1000}
      /&gt;
      {error &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"error"</span>&gt;</span>{error}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>}
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Post Comment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}
</code></pre>
<h3 id="heading-4-safe-url-handling">4. Safe URL Handling</h3>
<p>Be careful when handling URLs from user input:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// utils/url.js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> sanitizeUrl = <span class="hljs-function">(<span class="hljs-params">url</span>) =&gt;</span> {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> parsed = <span class="hljs-keyword">new</span> URL(url);
    <span class="hljs-comment">// Only allow http and https protocols</span>
    <span class="hljs-keyword">if</span> (![<span class="hljs-string">'http:'</span>, <span class="hljs-string">'https:'</span>].includes(parsed.protocol)) {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
    }
    <span class="hljs-keyword">return</span> parsed.toString();
  } <span class="hljs-keyword">catch</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
  }
};

<span class="hljs-comment">// In your component</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">LinkComponent</span>(<span class="hljs-params">{ href, children }</span>) </span>{
  <span class="hljs-keyword">const</span> safeUrl = sanitizeUrl(href);

  <span class="hljs-keyword">if</span> (!safeUrl) {
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>{children}<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span></span>;
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> 
      <span class="hljs-attr">href</span>=<span class="hljs-string">{safeUrl}</span> 
      <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span> 
      <span class="hljs-attr">rel</span>=<span class="hljs-string">"noopener noreferrer"</span>
    &gt;</span>
      {children}
    <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span></span>
  );
}
</code></pre>
<h2 id="heading-interview-insights-how-interviewers-test-xss-knowledge">Interview Insights: How Interviewers Test XSS Knowledge</h2>
<p>Understanding XSS isn't just about writing secure code—it's also about demonstrating your security awareness in interviews. Here's how interviewers typically approach this topic and what they're looking for.</p>
<h3 id="heading-common-interview-questions">Common Interview Questions</h3>
<p><strong>Question 1: "Walk me through how you would implement a comment system for a blog application. What security considerations would you keep in mind?"</strong></p>
<p><strong>What they're testing:</strong> Your ability to identify XSS risks in a common feature and propose mitigation strategies.</p>
<p><strong>Good answer structure:</strong></p>
<ol>
<li><p>Identify the XSS risk: "User comments are a classic XSS vector because they contain user-generated content"</p>
</li>
<li><p>Explain the attack scenario: "An attacker could submit a comment containing script tags that would execute when other users view the comment"</p>
</li>
<li><p>Propose specific solutions: "I would sanitize all user input using a library like DOMPurify, validate input lengths, and implement CSP headers"</p>
</li>
<li><p>Mention additional considerations: "I'd also implement rate limiting, content moderation, and ensure the backend validates and sanitizes data as well"</p>
</li>
</ol>
<p><strong>Question 2: "You're reviewing a React component that uses</strong> <code>dangerouslySetInnerHTML</code> to render user profiles. What red flags would you look for?"</p>
<p><strong>What they're testing:</strong> Your code review skills and understanding of XSS vulnerabilities.</p>
<p><strong>Good answer points:</strong></p>
<ul>
<li><p>Check if the HTML content is being sanitized before rendering</p>
</li>
<li><p>Look for direct insertion of user input without validation</p>
</li>
<li><p>Verify if the content source is trusted</p>
</li>
<li><p>Consider if <code>dangerouslySetInnerHTML</code> is necessary or if plain text rendering would suffice</p>
</li>
<li><p>Examine the allowed HTML tags and attributes</p>
</li>
</ul>
<p><strong>Question 3: "How would you implement a rich text editor that allows users to format their content but prevents XSS attacks?"</strong></p>
<p><strong>What they're testing:</strong> Your ability to balance functionality with security.</p>
<p><strong>Good answer structure:</strong></p>
<ol>
<li><p>Explain the allowlist approach: "I would define a strict allowlist of safe HTML tags and attributes"</p>
</li>
<li><p>Mention sanitization: "Use DOMPurify to sanitize content both on the client and server"</p>
</li>
<li><p>Discuss CSP: "Implement Content Security Policy to prevent inline scripts"</p>
</li>
<li><p>Consider alternatives: "For simpler use cases, consider markdown instead of raw HTML"</p>
</li>
</ol>
<p><strong>Question 4: "A user reports that clicking a link in your application executed unwanted JavaScript. How would you investigate and fix this?"</strong></p>
<p><strong>What they're testing:</strong> Your incident response approach and debugging skills.</p>
<p><strong>Good answer structure:</strong></p>
<ol>
<li><p>Immediate response: "First, I'd determine the scope—is this affecting multiple users or just one?"</p>
</li>
<li><p>Investigation: "I'd check for reflected XSS in URL parameters, examine how we handle user-generated links, and review recent code changes"</p>
</li>
<li><p>Mitigation: "Implement proper URL validation, sanitize link targets, and add rel='noopener noreferrer' to external links"</p>
</li>
<li><p>Prevention: "Set up monitoring for suspicious JavaScript execution and implement stricter CSP"</p>
</li>
</ol>
<h3 id="heading-what-interviewers-want-to-hear">What Interviewers Want to Hear</h3>
<p><strong>Security-first mindset:</strong> Show that you consider security implications from the beginning of feature development, not as an afterthought.</p>
<p><strong>Practical knowledge:</strong> Demonstrate familiarity with real-world tools and libraries (DOMPurify, CSP, etc.) rather than just theoretical concepts.</p>
<p><strong>Defense in depth:</strong> Explain how you'd implement multiple layers of protection rather than relying on a single solution.</p>
<p><strong>User impact awareness:</strong> Show that you understand how XSS attacks affect real users and business outcomes.</p>
<h3 id="heading-red-flags-to-avoid">Red Flags to Avoid</h3>
<ul>
<li><p>Dismissing XSS as "just a frontend problem" (it requires full-stack thinking)</p>
</li>
<li><p>Suggesting overly complex solutions when simple ones exist</p>
</li>
<li><p>Not mentioning user input validation</p>
</li>
<li><p>Ignoring the importance of server-side validation</p>
</li>
<li><p>Focusing only on technical solutions without considering user experience</p>
</li>
</ul>
<h2 id="heading-xss-prevention-practices-checklist">XSS Prevention Practices Checklist</h2>
<p>Here's your comprehensive checklist for preventing XSS vulnerabilities in frontend development:</p>
<h3 id="heading-development-phase">Development Phase</h3>
<ul>
<li><p>[ ] <strong>Default to safe rendering</strong>: Use React's default text rendering instead of <code>dangerouslySetInnerHTML</code> whenever possible</p>
</li>
<li><p>[ ] <strong>Sanitize all user input</strong>: Implement DOMPurify or similar sanitization library for any HTML content</p>
</li>
<li><p>[ ] <strong>Validate URLs</strong>: Check user-provided URLs for safe protocols (http/https only)</p>
</li>
<li><p>[ ] <strong>Use allowlists</strong>: Define strict allowlists for HTML tags and attributes rather than blocklists</p>
</li>
<li><p>[ ] <strong>Implement CSP</strong>: Configure Content Security Policy headers to prevent inline script execution</p>
</li>
<li><p>[ ] <strong>Validate on both ends</strong>: Implement validation on both client and server sides</p>
</li>
</ul>
<h3 id="heading-code-review-phase">Code Review Phase</h3>
<ul>
<li><p>[ ] <strong>Audit</strong> <code>dangerouslySetInnerHTML</code> usage: Every instance should be reviewed and justified</p>
</li>
<li><p>[ ] <strong>Check user input handling</strong>: Verify all user inputs are properly validated and sanitized</p>
</li>
<li><p>[ ] <strong>Review third-party content</strong>: Ensure external content (APIs, CMSs) is treated as untrusted</p>
</li>
<li><p>[ ] <strong>Examine URL handling</strong>: Check for proper validation of user-provided URLs and links</p>
</li>
<li><p>[ ] <strong>Verify escape sequences</strong>: Ensure special characters are properly escaped in all contexts</p>
</li>
</ul>
<h3 id="heading-testing-phase">Testing Phase</h3>
<ul>
<li><p>[ ] <strong>Test with malicious payloads</strong>: Try common XSS payloads in all input fields</p>
</li>
<li><p>[ ] <strong>Verify CSP effectiveness</strong>: Test that your CSP headers actually prevent script injection</p>
</li>
<li><p>[ ] <strong>Check different browsers</strong>: Ensure XSS protection works across different browsers</p>
</li>
<li><p>[ ] <strong>Test edge cases</strong>: Verify handling of empty inputs, very long inputs, and special characters</p>
</li>
<li><p>[ ] <strong>Validate sanitization</strong>: Ensure your sanitization logic handles all expected HTML elements</p>
</li>
</ul>
<h3 id="heading-deployment-phase">Deployment Phase</h3>
<ul>
<li><p>[ ] <strong>Configure production CSP</strong>: Set strict CSP headers for production environment</p>
</li>
<li><p>[ ] <strong>Enable security headers</strong>: Implement additional security headers (X-Content-Type-Options, X-Frame-Options)</p>
</li>
<li><p>[ ] <strong>Monitor for violations</strong>: Set up CSP violation reporting to detect potential attacks</p>
</li>
<li><p>[ ] <strong>Regular security audits</strong>: Schedule periodic security reviews of user-facing features</p>
</li>
<li><p>[ ] <strong>Keep dependencies updated</strong>: Regularly update sanitization libraries and security-related packages</p>
</li>
</ul>
<h3 id="heading-ongoing-maintenance">Ongoing Maintenance</h3>
<ul>
<li><p>[ ] <strong>Security training</strong>: Keep the team updated on latest XSS attack vectors and prevention techniques</p>
</li>
<li><p>[ ] <strong>Incident response plan</strong>: Have a clear process for handling security incidents</p>
</li>
<li><p>[ ] <strong>Documentation</strong>: Maintain clear guidelines for secure coding practices</p>
</li>
<li><p>[ ] <strong>Penetration testing</strong>: Conduct regular security testing of your applications</p>
</li>
</ul>
<hr />
<p>Remember, security isn't a one-time implementation—it's an ongoing practice that requires constant vigilance and updates. The techniques and tools discussed in this guide will help you build more secure applications, but staying informed about new attack vectors and defense strategies is equally important.</p>
<p>The goal isn't to become a security expert overnight, but to develop a security-conscious mindset that naturally considers these risks as you design and build frontend applications. With practice and attention to these principles, you'll be able to create applications that users can trust with their data and their safety.</p>
]]></content:encoded></item><item><title><![CDATA[Frontend System Design Interviews: A Practical Framework That Actually Works]]></title><description><![CDATA[Use RADIO framework—Requirements, Architecture, Data, Interfaces, Optimizations—to approach frontend system design interviews confidently]]></description><link>https://kshitijcodes.hashnode.dev/frontend-system-design-interviews-a-practical-framework-that-actually-works</link><guid isPermaLink="true">https://kshitijcodes.hashnode.dev/frontend-system-design-interviews-a-practical-framework-that-actually-works</guid><category><![CDATA[Frontend Development]]></category><category><![CDATA[frontend]]></category><category><![CDATA[System Design]]></category><category><![CDATA[interview]]></category><dc:creator><![CDATA[Kshitij Sharma]]></dc:creator><pubDate>Thu, 05 Jun 2025 19:19:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1749150516585/cf6e1b35-e148-4fa9-8a6e-1c67f261c8ba.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Frontend system design interviews used to terrify me. Unlike coding interviews where you solve a specific problem, system design feels so open-ended. "Design Instagram" – where do you even start? After bombing a few of these and eventually getting better at them, I've found that having a solid framework makes all the difference.</p>
<p>The framework I use is called <strong>RADIO</strong>, and it's basically a roadmap for tackling any frontend system design question without getting lost in the weeds. Let me walk you through it.</p>
<h2 id="heading-why-you-need-a-framework">Why You Need a Framework</h2>
<p>Here's the thing about system design interviews – they're intentionally vague. When someone says "design Instagram," they don't want you to build the entire app. They want to see how you think through complex problems, break them down, and communicate your thought process.</p>
<p>Without a framework, it's easy to jump around between topics, miss important parts, or spend 20 minutes talking about something the interviewer doesn't care about. Trust me, I've been there.</p>
<p>RADIO gives you structure: <strong>Requirements, Architecture, Data model, Interface definition, Optimizations</strong>. Each step builds on the previous one, and you'll naturally cover everything that matters.</p>
<h2 id="heading-r-requirements-figure-out-what-youre-actually-building">R - Requirements: Figure Out What You're Actually Building</h2>
<p>The first step is understanding what you're supposed to design. This might sound obvious, but "design Instagram" could mean a lot of things. Are we talking about the photo-sharing feed? Stories? Direct messaging? The camera interface?</p>
<p>You need to dig deeper and ask questions like you're working with a product manager on a new feature. Here are the types of questions I always ask:</p>
<p><strong>What's the core functionality?</strong> For Instagram, this might be viewing photos in a feed, posting new photos, or browsing user profiles. The interviewer usually has a specific area in mind.</p>
<p><strong>What features should I focus on?</strong> Even within the Instagram feed, there are tons of smaller features – liking posts, commenting, saving posts, sharing to stories. Figure out which ones are must-haves versus nice-to-haves.</p>
<p><strong>What platforms are we targeting?</strong> Mobile web, desktop, native apps? This affects your architecture decisions later.</p>
<p><strong>Any performance requirements?</strong> Should the feed load instantly? How many posts should we show initially?</p>
<p>Don't spend forever on this – maybe 10-15% of your interview time. But getting alignment here prevents you from going down the wrong path later.</p>
<p>Let's say we're designing Instagram's photo feed. After asking questions, we've agreed to focus on:</p>
<ul>
<li><p>Viewing an infinite scroll feed of photos</p>
</li>
<li><p>Liking and commenting on posts</p>
</li>
<li><p>Creating new photo posts</p>
</li>
<li><p>Mobile-first design with good performance</p>
</li>
</ul>
<p>Perfect. Now we know what we're building.</p>
<h2 id="heading-a-architecture-the-big-picture-components">A - Architecture: The Big Picture Components</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1749151009272/4483fd22-6b71-450b-92ad-14e8818ef59b.png" alt class="image--center mx-auto" /></p>
<p>Now comes the fun part – designing the actual system. Think of this as drawing boxes and arrows to show how different parts of your app work together.</p>
<p>For frontend system design, I usually think about these types of components:</p>
<p><strong>The Server</strong> – This is your API. Treat it as a black box that gives you data when you ask for it.</p>
<p><strong>Views/UI Components</strong> – These are what users see and interact with. For Instagram, you'd have a FeedView, PostView, CommentSection, etc.</p>
<p><strong>Controllers or State Managers</strong> – These handle business logic and coordinate between your UI and data. Think Redux, Zustand, or even just React hooks.</p>
<p><strong>Client Store</strong> – Where you keep data that multiple parts of your app need. User info, cached posts, app settings.</p>
<p>Here's how I'd break down Instagram's feed:</p>
<ul>
<li><p>The <strong>Server</strong> handles all the backend stuff – storing posts, user data, handling likes. It exposes APIs we can call.</p>
</li>
<li><p>The <strong>Feed Controller</strong> manages the feed logic – fetching posts, handling infinite scroll, coordinating updates when someone likes a post.</p>
</li>
<li><p>The <strong>Client Store</strong> keeps track of cached posts, user session data, and app state that persists across different views.</p>
</li>
<li><p>The <strong>Feed UI</strong> renders the actual interface – the list of posts, pull-to-refresh, loading states.</p>
</li>
<li><p>Individual <strong>Post Components</strong> render each photo post with all its interactions – likes, comments, share button.</p>
</li>
<li><p>The <strong>Post Creator</strong> handles the flow for adding new posts – photo upload, caption editing, posting.</p>
</li>
</ul>
<p>Draw this out with boxes and arrows. It doesn't need to be pretty, but it should show how data flows through your system. When a user likes a post, the flow might be: Post Component → Feed Controller → Server API → Update Client Store → Re-render UI.</p>
<h2 id="heading-d-data-model-what-information-lives-where">D - Data Model: What Information Lives Where</h2>
<p>Once you know your components, you need to think about what data each one needs. There are basically two types of data in frontend apps:</p>
<p><strong>Server data</strong> – Stuff that comes from your backend, like user profiles, posts, comments. This usually gets cached on the client.</p>
<p><strong>Client-only data</strong> – Temporary stuff that only matters in the browser, like which modal is open, form input values, loading states.</p>
<p>For Instagram's feed, here's what I'd map out:</p>
<ul>
<li><p><strong>Post data</strong> (from server): Each post needs an ID, the photo URL, caption, author info, like count, comments, timestamp. This lives in your client store after fetching from the server.</p>
</li>
<li><p><strong>User data</strong> (from server): User ID, username, profile picture, follower count. Also cached in your store.</p>
</li>
<li><p><strong>Feed state</strong> (client-only): Current scroll position, which posts are visible, loading state for infinite scroll, any error states.</p>
</li>
<li><p><strong>New post data</strong> (client input): When creating a post, you temporarily store the photo file, caption text, selected filters until the user hits "share."</p>
</li>
<li><p><strong>UI state</strong> (client-only): Which comments section is expanded, modal visibility, navigation state.</p>
</li>
</ul>
<p>The key is understanding what data needs to persist (like cached posts) versus what can disappear when you refresh the page (like which comment section is open).</p>
<h2 id="heading-i-interface-definition-how-everything-talks">I - Interface Definition: How Everything Talks</h2>
<p>Now you need to define how your components communicate with each other and with the server. This is basically your API design.</p>
<p><strong>Server APIs</strong> are HTTP requests. For Instagram's feed, you'd need:</p>
<ul>
<li><p>A <code>GET /feed</code> endpoint that returns posts for the user's timeline. It takes pagination parameters (maybe a cursor for infinite scroll) and returns a list of posts with all their data.</p>
</li>
<li><p>A <code>POST /posts</code> endpoint for creating new posts. Send the photo file, caption, and any metadata.</p>
</li>
<li><p>A <code>POST /posts/{id}/like</code> endpoint for liking posts.</p>
</li>
</ul>
<p><strong>Client APIs</strong> are just function calls between your components. Like:</p>
<p><code>feedController.loadMorePosts()</code> - Called when user scrolls near the bottom <code>feedController.likePost(postId)</code> - Called when user taps the heart <code>postCreator.sharePost(photoData, caption)</code> - Called when user finishes creating a post</p>
<p>The important thing is being clear about what data goes in and what comes back out. Your feed API might return something like:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"posts"</span>: [
    {
      <span class="hljs-attr">"id"</span>: <span class="hljs-string">"abc123"</span>,
      <span class="hljs-attr">"author"</span>: {
        <span class="hljs-attr">"username"</span>: <span class="hljs-string">"johndoe"</span>,
        <span class="hljs-attr">"profilePic"</span>: <span class="hljs-string">"https://..."</span>
      },
      <span class="hljs-attr">"photo"</span>: <span class="hljs-string">"https://..."</span>,
      <span class="hljs-attr">"caption"</span>: <span class="hljs-string">"Great sunset today!"</span>,
      <span class="hljs-attr">"likes"</span>: <span class="hljs-number">127</span>,
      <span class="hljs-attr">"createdAt"</span>: <span class="hljs-string">"2024-03-15T10:30:00Z"</span>
    }
  ],
  <span class="hljs-attr">"nextCursor"</span>: <span class="hljs-string">"xyz789"</span>,
  <span class="hljs-attr">"hasMore"</span>: <span class="hljs-literal">true</span>
}
</code></pre>
<h2 id="heading-o-optimizations-making-it-actually-work-well">O - Optimizations: Making It Actually Work Well</h2>
<p>This is where you get to show off your frontend chops. You've got the basic system designed, now how do you make it fast, accessible, and bulletproof?</p>
<p><strong>Performance optimization</strong> is huge for something like Instagram's feed:</p>
<ul>
<li><p>Virtual scrolling for handling thousands of posts without crashing the browser. Only render posts that are actually visible.</p>
</li>
<li><p>Image lazy loading so you're not downloading photos that users might never see.</p>
</li>
<li><p>Aggressive caching – once you've loaded a post, keep it in memory so switching between tabs is instant.</p>
</li>
<li><p>Optimistic updates for likes – update the UI immediately when someone taps the heart, then sync with the server in the background.</p>
</li>
<li><p>Code splitting so your initial bundle is small and loads fast.</p>
</li>
</ul>
<p><strong>User Experience</strong> improvements:</p>
<ul>
<li><p>Skeleton screens while posts are loading instead of blank white screens.</p>
</li>
<li><p>Infinite scroll that actually works smoothly – preload the next batch before users reach the bottom.</p>
</li>
<li><p>Offline support using service workers and cached data.</p>
</li>
<li><p>Good error handling when the network is flaky.</p>
</li>
</ul>
<p><strong>Accessibility</strong> considerations:</p>
<ul>
<li><p>Proper ARIA labels for screen readers.</p>
</li>
<li><p>Keyboard navigation support.</p>
</li>
<li><p>High contrast mode compatibility.</p>
</li>
<li><p>Alt text for images.</p>
</li>
</ul>
<p>You won't have time to cover everything, so pick 2-3 areas that are most relevant to the product or that you know well. If you're great at performance optimization, dive deep into that. If accessibility is your thing, talk about the challenges of making an image-heavy feed accessible.</p>
<h2 id="heading-putting-it-all-together">Putting It All Together</h2>
<p>The beauty of RADIO is that each step naturally flows into the next. Your requirements inform your architecture. Your architecture determines your data model. Your data model shapes your APIs. And your APIs give you concrete things to optimize.</p>
<p>Most importantly, you're having a conversation throughout this process. You're not just talking at the whiteboard – you're collaborating with your interviewer to build something together.</p>
<p>I've used this framework for designing everything from social media feeds to collaborative editors to e-commerce checkout flows. The specific details change, but the process stays the same.</p>
<h2 id="heading-final-tips">Final Tips</h2>
<p><strong>Don't try to be perfect.</strong> System design interviews aren't about finding the one correct answer. They're about demonstrating how you think through complex problems.</p>
<p><strong>Be opinionated.</strong> If you think infinite scroll is better than pagination for Instagram, say so and explain why. Interviewers want to see your decision-making process.</p>
<p><strong>Ask questions throughout.</strong> If you're not sure whether to focus on mobile or desktop, ask. If you're wondering about scale requirements, ask. The interviewer wants to help you succeed.</p>
<p><strong>Practice drawing.</strong> Whether it's on a whiteboard, tablet, or screen share, you'll be drawing diagrams. Get comfortable with basic boxes and arrows.</p>
<p>The next time someone asks you to "design Instagram," you won't panic. You'll start with requirements, sketch out your architecture, define your data model, specify your APIs, and discuss optimizations. Before you know it, you'll have designed a complete system that actually makes sense.</p>
<p>And honestly? That's a pretty good feeling.</p>
]]></content:encoded></item><item><title><![CDATA[Master Coin Change Problem (Leetcode 322) with This Easy Tutorial]]></title><description><![CDATA[Solve the coin change problem efficiently with this step-by-step guide, ensuring you find the minimum coins needed for any amount]]></description><link>https://kshitijcodes.hashnode.dev/master-coin-change-problem-leetcode-322-with-this-easy-tutorial</link><guid isPermaLink="true">https://kshitijcodes.hashnode.dev/master-coin-change-problem-leetcode-322-with-this-easy-tutorial</guid><category><![CDATA[Dynamic Programming]]></category><category><![CDATA[leetcode]]></category><category><![CDATA[leetcode-solution]]></category><category><![CDATA[leetcodedaily]]></category><dc:creator><![CDATA[Kshitij Sharma]]></dc:creator><pubDate>Fri, 23 May 2025 12:26:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1747999419471/e798b640-c03f-496b-839e-4d23a9ed4afc.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-the-problem">❓ The Problem</h2>
<blockquote>
<p>You’re given an array of coin denominations (e.g. <code>[1, 2, 5]</code>)<br />and a target amount (e.g. <code>11</code>).<br />Return the <strong>minimum number of coins</strong> needed to make up that amount.<br />If it's not possible, return <code>-1</code>.</p>
</blockquote>
<hr />
<h2 id="heading-what-youre-really-being-asked">🎯 What You’re Really Being Asked</h2>
<blockquote>
<p>Find the <strong>shortest path</strong> to a number, using only steps defined by the coins.</p>
</blockquote>
<p>For example:</p>
<pre><code class="lang-javascript">coins = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">5</span>]
amount = <span class="hljs-number">11</span>
</code></pre>
<p>You could make 11 in a ton of ways:</p>
<ul>
<li><p><code>1+1+1+...+1</code> (11 coins)</p>
</li>
<li><p><code>5+5+1</code> (3 coins)</p>
</li>
<li><p><code>2+2+2+5</code> (4 coins)</p>
</li>
</ul>
<p>But you want the way that uses the <strong>fewest total coins</strong>.</p>
<hr />
<h2 id="heading-why-this-problem-is-confusing">💣 Why This Problem Is Confusing</h2>
<p>Most people throw this at you:</p>
<pre><code class="lang-javascript">minCoins[i] = <span class="hljs-built_in">Math</span>.min(minCoins[i], <span class="hljs-number">1</span> + minCoins[i - coin])
</code></pre>
<p>And you’re left going:</p>
<ul>
<li><p>Where is this coming from?</p>
</li>
<li><p>Why is <code>minCoins[i]</code> being compared to itself?</p>
</li>
<li><p>What the hell is this “bottom-up” thing and why does it work?</p>
</li>
</ul>
<p>This blog answers <strong>all of that</strong>.</p>
<hr />
<h1 id="heading-step-by-step-plan-that-actually-makes-sense">✅ Step-by-Step Plan That Actually Makes Sense</h1>
<hr />
<h2 id="heading-step-1-define-the-meaning-of-dp">🧱 Step 1: Define the Meaning of DP</h2>
<p>We create:</p>
<pre><code class="lang-javascript">minCoins[i] = the minimum number <span class="hljs-keyword">of</span> coins needed to make amount i
</code></pre>
<p>We’re going to fill this from <code>0</code> up to <code>amount</code>.</p>
<hr />
<h3 id="heading-base-case">🚨 Base Case:</h3>
<pre><code class="lang-javascript">minCoins[<span class="hljs-number">0</span>] = <span class="hljs-number">0</span>
</code></pre>
<p>Why?</p>
<blockquote>
<p>Because it takes <strong>0 coins</strong> to make amount 0.<br />(You don’t need anything.)</p>
</blockquote>
<hr />
<h3 id="heading-initial-setup">🧱 Initial Setup:</h3>
<p>We assume all other amounts are <strong>impossible</strong> by default.<br />So we set them to “infinity” (<code>amount + 1</code> is safe):</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> minCoins = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Array</span>(amount + <span class="hljs-number">1</span>).fill(amount + <span class="hljs-number">1</span>);
minCoins[<span class="hljs-number">0</span>] = <span class="hljs-number">0</span>;
</code></pre>
<p>This says:</p>
<blockquote>
<p>“I don’t yet know how to make amount 1, 2, ..., <code>amount</code> —<br />but I’ll try to find better answers as I go.”</p>
</blockquote>
<hr />
<h2 id="heading-step-2-core-logic-build-up-the-answer">🧠 Step 2: Core Logic — Build Up the Answer</h2>
<p>Now the key idea:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">1</span>; i &lt;= amount; i++) {
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> coin <span class="hljs-keyword">of</span> coins) {
    <span class="hljs-keyword">if</span> (i - coin &gt;= <span class="hljs-number">0</span>) {
      minCoins[i] = <span class="hljs-built_in">Math</span>.min(minCoins[i], <span class="hljs-number">1</span> + minCoins[i - coin]);
    }
  }
}
</code></pre>
<p>Let's break it <strong>line by line</strong>:</p>
<hr />
<h3 id="heading-outer-loop-for-i-1-to-amount">🔁 Outer Loop: <code>for (i = 1 to amount)</code></h3>
<blockquote>
<p>“Let me solve for amount = 1, 2, 3, ..., <code>amount</code> one by one.”</p>
</blockquote>
<p>We’re building answers from the <strong>bottom up</strong>.</p>
<hr />
<h3 id="heading-inner-loop-for-coin-of-coins">🔁 Inner Loop: <code>for (coin of coins)</code></h3>
<blockquote>
<p>“For this current amount, let me try every coin I have.<br />Each one could be the <strong>last coin used</strong> to make this amount.”</p>
</blockquote>
<hr />
<h3 id="heading-the-real-brain-of-the-algorithm">🔥 The Real Brain of the Algorithm:</h3>
<pre><code class="lang-javascript">minCoins[i] = <span class="hljs-built_in">Math</span>.min(minCoins[i], <span class="hljs-number">1</span> + minCoins[i - coin]);
</code></pre>
<h3 id="heading-read-this-in-real-words">🚨 Read this in real words:</h3>
<blockquote>
<p>“If I use coin <code>c</code> now, then I only need to figure out how to build <code>amount - c</code>.<br />That’s <code>minCoins[i - coin]</code>.<br />So I take that answer, add 1 (for the current coin), and see if it's better than what I had before.”</p>
</blockquote>
<hr />
<h2 id="heading-example-coins-1-3-4-amount-6">📈 Example: <code>coins = [1, 3, 4], amount = 6</code></h2>
<p>Let’s walk through how we build <code>minCoins[6]</code>.</p>
<p>Start with:</p>
<pre><code class="lang-javascript">minCoins = [<span class="hljs-number">0</span>, ∞, ∞, ∞, ∞, ∞, ∞]
             <span class="hljs-number">0</span>   <span class="hljs-number">1</span>   <span class="hljs-number">2</span>   <span class="hljs-number">3</span>   <span class="hljs-number">4</span>   <span class="hljs-number">5</span>   <span class="hljs-number">6</span>
</code></pre>
<h3 id="heading-i-1">i = 1</h3>
<ul>
<li><p>Try 1: <code>1 + minCoins[0] = 1 + 0 = 1</code> ✅</p>
</li>
<li><p>Others invalid</p>
</li>
</ul>
<pre><code class="lang-javascript">minCoins = [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, ∞, ∞, ∞, ∞, ∞]
</code></pre>
<h3 id="heading-i-2">i = 2</h3>
<ul>
<li>Try 1: <code>1 + minCoins[1] = 1 + 1 = 2</code></li>
</ul>
<pre><code class="lang-javascript">minCoins = [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, ∞, ∞, ∞, ∞]
</code></pre>
<h3 id="heading-i-3">i = 3</h3>
<ul>
<li><p>Try 1: <code>1 + minCoins[2] = 1 + 2 = 3</code></p>
</li>
<li><p>Try 3: <code>1 + minCoins[0] = 1 + 0 = 1</code> ✅</p>
</li>
</ul>
<pre><code class="lang-javascript">minCoins = [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>, ∞, ∞, ∞]
</code></pre>
<h3 id="heading-i-4">i = 4</h3>
<ul>
<li><p>Try 1: <code>1 + minCoins[3] = 1 + 1 = 2</code></p>
</li>
<li><p>Try 3: <code>1 + minCoins[1] = 1 + 1 = 2</code></p>
</li>
<li><p>Try 4: <code>1 + minCoins[0] = 1 + 0 = 1</code> ✅</p>
</li>
</ul>
<pre><code class="lang-javascript">minCoins = [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, ∞, ∞]
</code></pre>
<h3 id="heading-i-5">i = 5</h3>
<ul>
<li><p>Try 1: <code>1 + minCoins[4] = 1 + 1 = 2</code> ✅</p>
</li>
<li><p>Try 3: <code>1 + minCoins[2] = 1 + 2 = 3</code></p>
</li>
<li><p>Try 4: <code>1 + minCoins[1] = 1 + 1 = 2</code></p>
</li>
</ul>
<pre><code class="lang-javascript">minCoins = [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, ∞]
</code></pre>
<h3 id="heading-i-6">i = 6</h3>
<ul>
<li><p>Try 1: <code>1 + minCoins[5] = 1 + 2 = 3</code></p>
</li>
<li><p>Try 3: <code>1 + minCoins[3] = 1 + 1 = 2</code> ✅</p>
</li>
<li><p>Try 4: <code>1 + minCoins[2] = 1 + 2 = 3</code></p>
</li>
</ul>
<pre><code class="lang-javascript">minCoins = [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>]
</code></pre>
<h3 id="heading-final-answer">✅ Final Answer:</h3>
<pre><code class="lang-javascript">minCoins[<span class="hljs-number">6</span>] = <span class="hljs-number">2</span>
</code></pre>
<p>You can form 6 using: <code>3 + 3</code> or <code>1 + 1 + 4</code> → both use 2 coins.</p>
<hr />
<h2 id="heading-forward-vs-reverse-loop">🔁 Forward vs Reverse Loop</h2>
<p>You don’t need <strong>reverse loop</strong> in this problem.</p>
<p>Why?</p>
<blockquote>
<p>Because every time you do:<br /><code>minCoins[i] = 1 + minCoins[i - coin]</code>,<br />you’re <strong>only reading past values</strong> (from smaller i’s)</p>
</blockquote>
<p>✅ Those values have already been finalized in earlier steps<br />✅ So forward loop works just fine</p>
<hr />
<p><strong>You’d use reverse loop only when:</strong></p>
<ul>
<li><p>You must not reuse the same item in the same iteration</p>
</li>
<li><p>Like in <strong>0/1 Knapsack</strong> (where each item can be used at most once)</p>
</li>
</ul>
<p>Not here. You can reuse coins as many times as you like.</p>
<hr />
<h2 id="heading-return-value">🔚 Return Value</h2>
<p>Finally:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">return</span> minCoins[amount] !== amount + <span class="hljs-number">1</span> ? minCoins[amount] : <span class="hljs-number">-1</span>;
</code></pre>
<p>If it’s still the "infinity" value → No solution found → return -1<br />Otherwise, return the best answer.</p>
<hr />
<h1 id="heading-tldr-mental-model">🧠 TL;DR Mental Model</h1>
<ul>
<li><p>For each amount <code>i</code></p>
</li>
<li><p>Try every coin <code>c</code></p>
</li>
<li><p>Think:</p>
</li>
</ul>
<blockquote>
<p>“If I use <code>c</code> now, how many coins did it take to form <code>i - c</code>?”<br />Add <code>1</code> for the current coin<br />Keep the best result</p>
</blockquote>
<p>That’s it. That’s the <strong>chain reaction</strong> you wanted to visualize.</p>
<hr />
<h2 id="heading-final-thoughts">💬 Final Thoughts</h2>
<p>Coin Change is a classic — not because it's hard,<br />but because it's so easy to explain <strong>badly</strong>.</p>
<p>If someone had just said:</p>
<blockquote>
<p>“Think of coins as <strong>steps</strong>, and amount as the top of a staircase.<br />You’re trying to reach the top with <strong>as few steps as possible</strong>,<br />trying every footstep that gets you closer,<br />and always remembering what the best path to each stair looked like.”</p>
</blockquote>
<p>You’d have gotten it <strong>on Day 1..</strong></p>
]]></content:encoded></item><item><title><![CDATA[Graph Traversal Made Simple: Your First Guide to BFS & DFS Code (For New Developers)]]></title><description><![CDATA[Explore BFS and DFS in graph traversal with a fun cookie analogy, perfect for beginners. Learn coding differences and key concepts effortlessly]]></description><link>https://kshitijcodes.hashnode.dev/graph-traversal-made-simple-your-first-guide-to-bfs-and-dfs-code-for-new-developers</link><guid isPermaLink="true">https://kshitijcodes.hashnode.dev/graph-traversal-made-simple-your-first-guide-to-bfs-and-dfs-code-for-new-developers</guid><category><![CDATA[graph traversal]]></category><category><![CDATA[DSA]]></category><category><![CDATA[DSA-SERIES]]></category><category><![CDATA[design patterns]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Kshitij Sharma]]></dc:creator><pubDate>Thu, 22 May 2025 12:36:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1747917009658/2da1b480-11b1-4773-8195-c81e9ae8a5ed.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Forget about nodes, edges, stacks, and queues for now. Let's imagine there's an empty <strong>basket</strong>, a <strong>chocolate cookie</strong> (our starting point!), and an empty <strong>plate</strong>.</p>
<p>All we do in these graph traversals, be it BFS or DFS, is follow a simple process:</p>
<ol>
<li><p>We pick a cookie from the basket.</p>
</li>
<li><p>We find all its directly connected cookies (of different flavors like oats, almond).</p>
</li>
<li><p>We put these newly found, unvisited cookies into the basket.</p>
</li>
<li><p>We take a bite from the cookie we picked (meaning, we process it).</p>
</li>
<li><p>Then, we put this tasted cookie onto our plate.</p>
</li>
</ol>
<p>We repeat this: pick a new cookie from the basket, find its connected cookies, add them to the basket, take a bite from the picked cookie, and add it to the plate which already holds the cookies we've tasted. We keep going until the basket is empty. At the end, we return the plate of tasted cookies, showing the order we visited them.</p>
<p>The <strong>only and only difference</strong> between BFS and DFS Traversals is in <em>what order we pick the cookies from the basket</em>. This difference in the order of picking cookies from the basket decides how the maze of connections will be traversed: either spreading out (breadth-first) or going deep (depth-first).</p>
<p>Now let's see how the code pulls it off.</p>
<p>First, let's imagine our cookie connections. It's like a map telling us which cookies are next to each other:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Our yummy cookie connections!</span>

<span class="hljs-comment">// This is like our graph's adjacency list.</span>

<span class="hljs-keyword">const</span> cookieConnections = {

  <span class="hljs-string">'Chocolate'</span>: [<span class="hljs-string">'Almond'</span>, <span class="hljs-string">'Oats'</span>],      <span class="hljs-comment">// Chocolate cookie is connected to Almond and Oats</span>

  <span class="hljs-string">'Almond'</span>: [<span class="hljs-string">'Chocolate'</span>, <span class="hljs-string">'Coconut'</span>], <span class="hljs-comment">// Almond is connected to Chocolate and Coconut</span>

  <span class="hljs-string">'Oats'</span>: [<span class="hljs-string">'Chocolate'</span>, <span class="hljs-string">'Cinnamon'</span>],  <span class="hljs-comment">// Oats is connected to Chocolate and Cinnamon</span>

  <span class="hljs-string">'Coconut'</span>: [<span class="hljs-string">'Almond'</span>],              <span class="hljs-comment">// Coconut is connected to Almond</span>

  <span class="hljs-string">'Cinnamon'</span>: [<span class="hljs-string">'Oats'</span>]                <span class="hljs-comment">// Cinnamon is connected to Oats</span>

};


<span class="hljs-comment">// We'll start our tasting adventure with the Chocolate cookie</span>

<span class="hljs-keyword">const</span> firstCookieToTaste = <span class="hljs-string">'Chocolate'</span>;
</code></pre>
<h3 id="heading-the-code-setup-before-the-main-while-loop"><strong>The Code Setup (Before the Main `while` Loop)</strong></h3>
<p>Here we simply set up our basket, the plate, and get ready to taste. We also need a way to remember which cookies we've already seen or put in the basket, so we don't process them again. Let's call this cookiesWeKnow. We then put the first chocolate cookie into the basket and mark it as known.</p>
<p>This setup is almost identical for both BFS and DFS:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">startTasting</span>(<span class="hljs-params">connections, startCookie, isBFS</span>) </span>{ <span class="hljs-comment">// Added a parameter to show which function it is for clarity</span>

    <span class="hljs-keyword">let</span> basket = []; <span class="hljs-comment">// Our basket for cookies to try</span>

    <span class="hljs-keyword">let</span> plate = [];  <span class="hljs-comment">// Our plate for cookies we've already tasted</span>

    <span class="hljs-keyword">let</span> cookiesWeKnow = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>(); <span class="hljs-comment">// To remember cookies we've identified (either in basket or on plate)</span>


    <span class="hljs-comment">// Put the first chocolate cookie in the basket to kick things off</span>

    <span class="hljs-keyword">if</span> (connections[startCookie]) { <span class="hljs-comment">// Make sure the starting cookie exists</span>

        basket.push(startCookie);

        cookiesWeKnow.add(startCookie); <span class="hljs-comment">// Mark it as known</span>

    } <span class="hljs-keyword">else</span> {

        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Starting cookie not found in connections!"</span>);

        <span class="hljs-keyword">return</span> plate;

    }

    <span class="hljs-comment">// ... rest of the traversal logic will go here ...</span>
</code></pre>
<h3 id="heading-the-main-tasting-cycle-the-while-loop"><strong>The Main Tasting Cycle (The While Loop)</strong></h3>
<p>This while loop represents the entire cycle of picking a cookie, finding its connected cookies, adding them to the basket, tasting the picked cookie, and putting it on the plate, just like we discussed earlier. It will keep going as long as there are cookies left in the basket.</p>
<p>const currentCookie represents the cookie we have just picked from the basket.</p>
<p>Now here's the <strong>first big difference</strong> in BFS and DFS code that changes how we traverse the graph: how we pick currentCookie using JavaScript array methods .pop() and .shift().</p>
<ul>
<li><p><strong>Stack Data Structure (DFS) using an array:</strong> .pop() takes the <strong>last</strong> element from the basket array (Last-In, First-Out or LIFO). Think of it as taking a cookie from the <strong>top</strong> of a pile in the basket.</p>
</li>
<li><p><strong>Queue Data Structure (BFS) using an array:</strong> .shift() takes the <strong>first</strong> element from the basket array (First-In, First-Out or FIFO). Think of it as taking the cookie that has been waiting the <strong>longest</strong> in a line in the basket.</p>
</li>
</ul>
<p>In what order we put the cookies in the basket and, crucially, in what order we pick them up to taste, is what decides how the traversal will happen.</p>
<p>Let's see it in context for <strong>BFS</strong>:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// For BFS:</span>

    <span class="hljs-keyword">while</span> (basket.length &gt; <span class="hljs-number">0</span>) {

        <span class="hljs-comment">// Pick the cookie from the FRONT of the basket (FIFO)</span>

        <span class="hljs-keyword">const</span> currentCookie = basket.shift(); <span class="hljs-comment">// Magic for BFS!</span>


        <span class="hljs-comment">// Take a bite and put it on our plate</span>

        plate.push(currentCookie);


        <span class="hljs-comment">// Now, let's look for its connected cookies...</span>

        <span class="hljs-comment">// ... (for loop for neighbors comes next) ...</span>

And <span class="hljs-keyword">for</span> DFS:

JavaScript

<span class="hljs-comment">// For DFS:</span>

    <span class="hljs-keyword">while</span> (basket.length &gt; <span class="hljs-number">0</span>) {

        <span class="hljs-comment">// Pick the cookie from the TOP of the basket pile (LIFO)</span>

        <span class="hljs-keyword">const</span> currentCookie = basket.pop(); <span class="hljs-comment">// Magic for DFS!</span>


        <span class="hljs-comment">// Take a bite and put it on our plate</span>

        plate.push(currentCookie);


        <span class="hljs-comment">// Now, let's look for its connected cookies...</span>

        <span class="hljs-comment">// ... (for loop for neighbors comes next) ...</span>
</code></pre>
<h3 id="heading-finding-and-adding-connected-cookies-the-for-loop"><strong>Finding and Adding Connected Cookies (The For Loop)</strong></h3>
<p>Earlier we understood the order in which we pick a cookie from the basket is influenced by .pop() (for DFS) and .shift() (for BFS). Now let's focus on how the newly found connected cookies are added to the basket.</p>
<p><strong>For BFS:</strong></p>
<p>In BFS, after we pick a cookie (using .shift()) and put it on our plate, we find its connected cookies. We then run a straightforward ascending order for loop (from the first connected cookie to the last). If a connected cookie is new to us, we add it to the end of the basket (queue).</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Inside the BFS while loop, after plate.push(currentCookie):</span>

        <span class="hljs-keyword">const</span> connectedCookies = connections[currentCookie] || [];


        <span class="hljs-comment">// In BFS, we run a straightforward ascending order for loop</span>

        <span class="hljs-comment">// to find new cookies and add them to the end of the basket (queue).</span>

        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; connectedCookies.length; i++) {

            <span class="hljs-keyword">const</span> nextCookie = connectedCookies[i];

            <span class="hljs-keyword">if</span> (!cookiesWeKnow.has(nextCookie)) {

                cookiesWeKnow.add(nextCookie);

                basket.push(nextCookie); <span class="hljs-comment">// Add to the end (FIFO style)</span>

            }

        }

    } <span class="hljs-comment">// End of BFS while loop</span>

    <span class="hljs-keyword">return</span> plate;

} <span class="hljs-comment">// End of BFS tasting function</span>
</code></pre>
<p><strong>For DFS:</strong></p>
<p>In DFS, after we pick a cookie (using .pop()) and put it on our plate, we also find its connected cookies. But here's a subtle and important detail: we typically run a reverse for loop (from the last connected cookie back to the first) when adding these cookies to the basket (stack).</p>
<p>Why? This is often done so that the traversal happens from "left-to-right" conceptually, if you imagine the connected cookies listed in a certain order (e.g., if 'Chocolate' is connected to ['Almond', 'Oats'], we want to explore 'Almond' and its path before 'Oats'). Since we use .pop() (Last-In, First-Out) for DFS, if we find neighbors ['Almond', 'Oats'] and add 'Oats' first, then 'Almond' to the basket, 'Almond' will be on top and be picked next. This achieves the "left-to-right" exploration. If we used a forward loop to add them, 'Oats' would be picked first, leading to an (equally valid, but different) "right-to-left" traversal relative to their order in the list.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Inside the DFS while loop, after plate.push(currentCookie):</span>

        <span class="hljs-keyword">const</span> connectedCookies = connections[currentCookie] || [];


        <span class="hljs-comment">// In DFS, we run a reverse for loop to add connected cookies to the basket (stack).</span>

        <span class="hljs-comment">// This ensures that if connections are [A, B], B is pushed, then A is pushed.</span>

        <span class="hljs-comment">// So, A (the "leftmost" or first in the original list) is on top and gets explored next.</span>

        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = connectedCookies.length - <span class="hljs-number">1</span>; i &gt;= <span class="hljs-number">0</span>; i--) {

            <span class="hljs-keyword">const</span> nextCookie = connectedCookies[i];

            <span class="hljs-keyword">if</span> (!cookiesWeKnow.has(nextCookie)) {

                cookiesWeKnow.add(nextCookie);

                basket.push(nextCookie); <span class="hljs-comment">// Add to the end, which is the top for .pop()</span>

            }

        }

    } <span class="hljs-comment">// End of DFS while loop</span>

    <span class="hljs-keyword">return</span> plate;

} <span class="hljs-comment">// End of DFS tasting function</span>
</code></pre>
<h3 id="heading-the-main-difference-in-a-nutshell"><strong>The Main Difference in a Nutshell</strong></h3>
<ul>
<li><p>In simple words, the key difference is that in <strong>DFS</strong> (Depth-First Search), we keep "piling up" newly found connected cookies, and the next cookie we taste is often one that was very recently added to the top of this pile (because we .pop() the newest). This makes us go deeper and deeper along one path of connections.</p>
</li>
<li><p>On the other hand, <strong>BFS</strong> (Breadth-First Search) goes in a more "orderly" fashion. Cookies are picked one-by-one from the beginning of the line in the basket (because we .shift() the oldest). This leads to an equal traversal spread, exploring all cookies at the current "layer" or distance before moving to the next layer.</p>
</li>
</ul>
<hr />
<p>And that's how the code, with just a small change in picking from the basket (and how we strategically add to it for DFS), pulls off two very different ways of exploring our delicious world of cookies!</p>
<p>Let's see the order of tasted cookies for our example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// To make the functions above runnable, let's wrap them:</span>


<span class="hljs-comment">// BFS Function</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bfsTraversal</span>(<span class="hljs-params">connections, startCookie</span>) </span>{

    <span class="hljs-keyword">let</span> basket = [];

    <span class="hljs-keyword">let</span> plate = [];

    <span class="hljs-keyword">let</span> cookiesWeKnow = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>();


    <span class="hljs-keyword">if</span> (!connections[startCookie]) <span class="hljs-keyword">return</span> plate;


    basket.push(startCookie);

    cookiesWeKnow.add(startCookie);


    <span class="hljs-keyword">while</span> (basket.length &gt; <span class="hljs-number">0</span>) {

        <span class="hljs-keyword">const</span> currentCookie = basket.shift();

        plate.push(currentCookie);

        <span class="hljs-keyword">const</span> connectedCookies = connections[currentCookie] || [];

        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; connectedCookies.length; i++) {

            <span class="hljs-keyword">const</span> nextCookie = connectedCookies[i];

            <span class="hljs-keyword">if</span> (!cookiesWeKnow.has(nextCookie)) {

                cookiesWeKnow.add(nextCookie);

                basket.push(nextCookie);

            }

        }

    }

    <span class="hljs-keyword">return</span> plate;

}


<span class="hljs-comment">// DFS Function</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">dfsTraversal</span>(<span class="hljs-params">connections, startCookie</span>) </span>{

    <span class="hljs-keyword">let</span> basket = [];

    <span class="hljs-keyword">let</span> plate = [];

    <span class="hljs-keyword">let</span> cookiesWeKnow = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>();


    <span class="hljs-keyword">if</span> (!connections[startCookie]) <span class="hljs-keyword">return</span> plate;


    basket.push(startCookie);

    cookiesWeKnow.add(startCookie);


    <span class="hljs-keyword">while</span> (basket.length &gt; <span class="hljs-number">0</span>) {

        <span class="hljs-keyword">const</span> currentCookie = basket.pop();

        plate.push(currentCookie);

        <span class="hljs-keyword">const</span> connectedCookies = connections[currentCookie] || [];

        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = connectedCookies.length - <span class="hljs-number">1</span>; i &gt;= <span class="hljs-number">0</span>; i--) {

            <span class="hljs-keyword">const</span> nextCookie = connectedCookies[i];

            <span class="hljs-keyword">if</span> (!cookiesWeKnow.has(nextCookie)) {

                cookiesWeKnow.add(nextCookie);

                basket.push(nextCookie);

            }

        }

    }

    <span class="hljs-keyword">return</span> plate;

}


<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"BFS Tasted Order:"</span>, bfsTraversal(cookieConnections, firstCookieToTaste).join(<span class="hljs-string">', '</span>));

<span class="hljs-comment">// Expected BFS Output: Chocolate, Almond, Oats, Coconut, Cinnamon</span>


<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"DFS Tasted Order:"</span>, dfsTraversal(cookieConnections, firstCookieToTaste).join(<span class="hljs-string">', '</span>));

<span class="hljs-comment">// Expected DFS Output: Chocolate, Almond, Coconut, Oats, Cinnamon</span>

<span class="hljs-comment">// (This DFS order explores Chocolate -&gt; Almond -&gt; Coconut fully, then backtracks to Chocolate's other child Oats -&gt; Cinnamon)</span>
</code></pre>
<p>Checkout these youtube shorts where a <strong>Queue or Stack</strong> is the basket, and <strong>Processed</strong> is the tasted cookies Plate.</p>
<p><strong>For BFS:</strong> <a target="_blank" href="https://www.youtube.com/shorts/umHJzlKFGlU">https://www.youtube.com/shorts/umHJzlKFGlU</a></p>
<p><strong>For DFS:</strong> <a target="_blank" href="https://www.youtube.com/shorts/5Kl3L3kdGbs">https://www.youtube.com/shorts/5Kl3L3kdGbs</a></p>
]]></content:encoded></item><item><title><![CDATA[The Illusion of Speed: Unveiling Next.js' Perceived Faster Load Times]]></title><description><![CDATA[A Deep Dive into how Nextjs achieves such lightning fast loading speed]]></description><link>https://kshitijcodes.hashnode.dev/the-illusion-of-speed-unveiling-nextjs-perceived-faster-load-times</link><guid isPermaLink="true">https://kshitijcodes.hashnode.dev/the-illusion-of-speed-unveiling-nextjs-perceived-faster-load-times</guid><category><![CDATA[Next.js]]></category><category><![CDATA[Next.js 13.2]]></category><category><![CDATA[React]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[webdev]]></category><dc:creator><![CDATA[Kshitij Sharma]]></dc:creator><pubDate>Wed, 18 Oct 2023 04:13:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1697602156790/09741759-0ac2-4ee8-a4f6-e25d0877b7c3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this TikTok and reel world, user attention is ever-decreasing, making the loading speed paramount. Users crave speed, responsiveness, and smooth interactions. To meet this demand, developers employ techniques to enhance perceived performance. Skeleton screens, fun facts on load, and dynamic icons (like a moving car on a cab app's map) all grab and hold user attention.</p>
<p>Next.js, a robust React framework, utilizes Server-Side Rendering (SSR) and client-side hydration to optimize how users perceive load times—exemplifying one such effective technique.</p>
<h2 id="heading-understanding-the-perceived-speed">Understanding the Perceived Speed</h2>
<p>When you visit a website and the content appears immediately, it gives the impression of a fast-loading page, even if the data fetching time remains constant (compared to web apps built using other languages and frameworks). Next.js uses this phenomenon by providing pre-rendered HTML content for the initial view, which swiftly gives users a sense of responsiveness. This means that users can see the content on their screen without delay, making the experience more seamless and enjoyable.</p>
<h2 id="heading-the-nextjs-approach">The Next.js Approach</h2>
<p>Next.js, built on React, combines the best of server-side rendering and client-side interactivity. Here's how it achieves the illusion of speed:</p>
<p><strong>Server-Side Rendering (SSR)</strong>:</p>
<p>Next.js employs SSR to pre-render the page on the server based on the requested URL. This pre-rendered HTML content is sent as the initial response to the user's request on the browser.</p>
<p><strong>Client-Side Hydration</strong>:</p>
<p>Simultaneously, Next.js transmits the required JavaScript bundle for the page. As this JavaScript loads and runs on the client side, React takes over and "hydrates" the initial HTML. This process adds interactivity, transforming the static content into a fully functional and interactive React application.</p>
<p>By separating the rendering of the initial content on the server and the application logic on the client side, Next.js balances perceived speed and interactivity.</p>
<h2 id="heading-the-illusion-at-play">The Illusion at Play</h2>
<p>The trick here is all about how users perceive it. The first HTML content pops up fast, giving the illusion of a lightning-fast page load. The subsequent hydration process amplifies this impression, making the page interactive and fully functional. Users are captivated right from the start, staying immersed in the experience.</p>
<h2 id="heading-benefits-beyond-perception">Benefits Beyond Perception</h2>
<p>While this perceived speed greatly enhances user satisfaction, it also has tangible benefits. Search engines can efficiently crawl and index the pre-rendered content, improving the application's search engine optimization (SEO). Additionally, users on slower devices or connections perceive a faster experience due to the swift display of the initial content.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Next.js optimizes user experience by swiftly displaying an initial application view, giving a sense of speed. Using SSR with client-side hydration, Next.js efficiently prioritizes content delivery and interactivity. Striking the right balance keeps users engaged and satisfied. In today's fast-paced digital era, it's all about creating experiences that perform well and feel lightning-fast for the end-users.</p>
]]></content:encoded></item><item><title><![CDATA[Multiple Threads of Execution & Process Utilization in Linux]]></title><description><![CDATA[Resource Utilization by Processes, Multiple Threads of Execution, Load Averages, vmstat, Logging, Logging Manual Messages, Log Management with logrotate]]></description><link>https://kshitijcodes.hashnode.dev/multiple-threads-of-execution-process-utilization-in-linux</link><guid isPermaLink="true">https://kshitijcodes.hashnode.dev/multiple-threads-of-execution-process-utilization-in-linux</guid><category><![CDATA[Linux]]></category><category><![CDATA[linux for beginners]]></category><category><![CDATA[Devops]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[linux-basics]]></category><dc:creator><![CDATA[Kshitij Sharma]]></dc:creator><pubDate>Thu, 17 Nov 2022 15:21:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1668698465851/3uSrOonEY.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Until now, we have seen that everything in Linux runs on processes. These processes take some resources to execute, like the memory and <a target="_blank" href="https://blog.gauranggaur.com/processes-in-linux-how-linux-works-internally-explained-in-detail#heading-cpu-time">CPU Time</a>. We will talk about how the processes utilize these resources behind the scenes and the logging that system does. </p>
<h1 id="heading-resource-utilization-by-processes">Resource Utilization by Processes</h1>
<p>Earlier, while talking about processes, we came across a command known as <a target="_blank" href="https://blog.gauranggaur.com/processes-in-linux-how-linux-works-internally-explained-in-detail#heading-top-command">‘top’</a>. <code>top</code> is similar to <a target="_blank" href="https://blog.gauranggaur.com/processes-in-linux-how-linux-works-internally-explained-in-detail#heading-ps-aux-command">‘ps aux’</a> but rather than giving us a snapshot of the resource utilization by the processes, it shows us a live version where it keeps updating the details after every 3-5 seconds.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668696224972/G8fxVS4w1.png" alt="Screenshot from 2022-11-16 14-21-59.png" /></p>
<p>Earlier, we only understood the columns and the data in the rows but left the part above it. Let us go through the key-value pairs. </p>
<p><code>top – 14:21:58</code> tells us the current time. <code>up 4:40</code> means the system has been running for 4 hours 40 minutes. <code>1 user</code> means only one user is currently logged in the system. <code>load average</code> tells how much load the system is taking in form of averages (We will discuss this later in more detail).  </p>
<p>The <code>Tasks</code> section tells us that a total of 263 tasks exist. Out of which 1 is running, 262 are sleeping, 0 stopped, and 0 are <a target="_blank" href="https://blog.gauranggaur.com/processes-in-linux-how-linux-works-internally-explained-in-detail#heading-zombie-process">zombie</a>.<br />In the <code>%Cpu(s)</code> section, <code>0.9us</code> means the percentage of CPU time used by the processes that are not nice (Understand the concept of ‘Nice’ <a target="_blank" href="https://blog.gauranggaur.com/processes-in-linux-how-linux-works-internally-explained-in-detail#heading-cpu-time">here</a>). <code>0.8 sy</code> is for the processes run by the system or Kernel itself. <code>0.0 ni</code> is for the processes that are nice or have nice value. <code>97.9 id</code> is the percentage of CPU Time that is idle.  </p>
<p>Our CPU/Kernel is always looking for the input/output processes in the system executed by the user. CPU allocates a separate waiting time to catch and process these input requests. So, <code>0.4 wa</code> is the percentage of time currently invested by the CPU in waiting for input/output streams.  </p>
<p>It may happen that sometimes we interrupt a software or a hardware device interrupts some process. The CPU has to listen to these as well. <code>0.0 hi, 0.0 si</code> tells us the amount of CPU time going into Hardware interrupts and Software interrupts.  </p>
<p><code>0.0 st</code> tells us the amount of time something is stealing out of the Operating System. It can be some other OS like Windows on the same machine if you have installed one.<br /><code>MiB mem</code> is for memory utilization, and <code>MiB swap</code> is for <a target="_blank" href="https://blog.gauranggaur.com/filesystem-partitions-inodes-in-linux-a-deep-dive#heading-swap-memory">Swap Memory</a> utilization. The value numbers are in megabytes.  </p>
<h1 id="heading-checking-resource-utilization-by-a-single-process">Checking Resource Utilization by a Single Process</h1>
<p>Maybe, you want to monitor just one process. It can be because the process is slowing down your system,  </p>
<p>There may come a situation where a process is slowing down your system, like Google Chrome, after keeping too many tabs open. And you want to monitor that particular process that we suspect might be slowing down our system. </p>
<p>Run the command <code>top –p [PID]</code> where –p stands for PID. You can find the PID of a running process from the first column of the <code>top</code> command data. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668696314946/4wJyeHSNC.png" alt="Screenshot from 2022-11-16 17-52-16.png" /></p>
<p>Here you can see the result of the <code>top –p 1</code> command. It shows us the details of the <a target="_blank" href="https://blog.gauranggaur.com/processes-in-linux-how-linux-works-internally-explained-in-detail#heading-mother-process">mother process</a>.  </p>
<h1 id="heading-list-of-files-lsof">List of Files (lsof)</h1>
<p>Let us imagine a scenario where you plug in the USB in your computer and open a code file directly from the USB via VSCode. Or maybe, you opened a movie via VLC Media Player directly from the USB. Now, after closing everything that you opened directly from the pen drive, if you try to right-click and ‘eject’ the USB, it sometimes may say something like, the device is currently in use. You cannot eject it. That too after closing VSCode and VLC Media Player. </p>
<p>It means there is a file inside the pen drive folder that might be getting used by a process in the system. </p>
<blockquote>
<p>Everything is a Process. In this context, even the VSCode and VLC Media Player are Processes. </p>
</blockquote>
<p>There is a command <code>lsof</code> to know what files are currently in use by a Process. <code>ls</code> means list, <code>o</code> means of, and <code>f</code> means files. It gives us a list of all the files currently in use with the associated process.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668696437089/9tEQWZSTR.png" alt="Screenshot from 2022-11-16 18-43-00.png" /></p>
<p>It will help you find out why you cannot eject a particular device by letting you know what process is utilizing a file of your device. Now you can kill that process with the <code>kill</code> command using its PID. </p>
<h1 id="heading-multiple-threads-of-execution">Multiple Threads of Execution</h1>
<p>Let us assume you are playing a car-racing multiplayer game. There are two cars. You are controlling car 1 and the other player, car 2. Wherever you two are sitting in the world, your movements will get reflected in each other’s screen. If the other player moves his car left/right, you will see it on your screen. </p>
<p>Two things are happening in your system while you play the multiplayer game on your computer: </p>
<ul>
<li>The position of the player is updated. </li>
<li>The position of the player is sent to the internet.  </li>
</ul>
<p>It proves that the Kernel provides multiple ways of execution in the same program. Let us take one more example to understand this better. </p>
<p>Let us assume you are writing code in some editor, and it is automatically getting saved. So, two things are happening here. </p>
<ul>
<li>Code Editing </li>
<li>Auto-saving </li>
</ul>
<p>As we know, all software are processes. Let us understand this above concept in those terms. Now the process has one piece of code that is doing one thing. It can be updating your position in the game based on keyboard input or editing the code written by you. The other piece of code in the process is doing some other thing. It can be sending your changed position to the server so the other player can receive it or auto-saving your written code in the code editor.  </p>
<p>These two ‘things’ that the process is executing parallelly are called ‘multiple threads of execution’ and are also known as ‘Lightweight Processes’. </p>
<p>There is a way to check all the processes running along with their threads by running the command <code>ps m</code>.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668696510536/-miRtjnYK.png" alt="Screenshot from 2022-11-17 09-04-31.png" /></p>
<p>The threads with <code>-</code> in PID and TTY columns are threads. As the <code>bash</code> and <code>ps m</code> processes only have one thread of execution, there is only one line of <code>-</code> or thread under them. </p>
<h1 id="heading-load-averages">Load Averages</h1>
<p>Run the command <code>uptime</code> </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668696573117/XHa6CERIG.png" alt="Screenshot from 2022-11-17 09-17-57.png" /></p>
<p>It is the same as the first line of the <code>top</code> command output. Earlier, we left Load Averages for later. Let us understand them now. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668695823599/7AF1suLOh.png" alt="ls -la etc  less (7) (1).png" /></p>
<p>Load Average is a good way of observing the load on the CPU. These three numbers mean how much the load average is on your CPU at the interval of 1 minute, 5 minutes, and 15 minutes. </p>
<p>What does the CPU load mean? It means the average number of processes waiting to be executed by the CPU.  </p>
<p>Let us say you have a 1-core CPU. Assume it is like a single-lane road. It is busy during rush hour, and the lane is running at full capacity, so the load average is 1. If the traffic gets double what the road can handle at once, the load average will be 2. If the lane can handle 10 cars at once, but only five cars are there, the load average will be 0.5.  </p>
<p>If the CPU load average is 1, it does not mean the CPU is slow. Because all CPUs today do not come with a single-core CPU (Understand the concept of cores and CPU Time in detail <a target="_blank" href="https://blog.gauranggaur.com/processes-in-linux-how-linux-works-internally-explained-in-detail#heading-cpu-time">here</a>). </p>
<p>If your CPU has 4 cores (quad-core), it is like having 4 road lanes. And now, if the CPU load is 1, then it means the CPU is only using 25% of its capacity.  </p>
<h1 id="heading-vmstat-command">vmstat command</h1>
<p>By running the command <code>vmstat</code>, you can see a detailed version of how much memory your system is utilizing right now. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668696635080/G87Iba3Nu.png" alt="Screenshot from 2022-11-17 10-20-49.png" /></p>
<p>Let us go through the output.  </p>
<p><strong><a target="_blank" href="https://blog.gauranggaur.com/filesystem-partitions-inodes-in-linux-a-deep-dive#heading-filesystem-fs-hierarchy">procs</a> section</strong> </p>
<ul>
<li><p><code>r</code> - processes at runtime.  </p>
</li>
<li><p><code>b</code> - processes at uninterruptible sleep.  </p>
</li>
</ul>
<p><strong>memory section</strong> </p>
<ul>
<li><p><code>swpd</code> - how much swap memory we have.  </p>
</li>
<li><p><code>free</code> - free memory we have </p>
</li>
<li><p><code>buff</code> - memory for buffer </p>
</li>
<li><p><code>cache</code> - memory for caching </p>
</li>
</ul>
<p><strong>swap section</strong> </p>
<ul>
<li><p><code>si</code> - memory swapped in the disk </p>
</li>
<li><p><code>so</code> - memory swapped out of the disk </p>
</li>
</ul>
<p><strong>io section</strong> </p>
<ul>
<li><p><code>bi</code> - blocks received from a block device </p>
</li>
<li><p><code>bo</code> - blocks sent out to a block device </p>
</li>
</ul>
<p><strong>system section</strong> </p>
<ul>
<li><p><code>in</code> - number of interrupts per second </p>
</li>
<li><p><code>cs</code> - how many context switches are there, which means how many processes it is giving time to per second </p>
</li>
</ul>
<p><strong>cpu section</strong> </p>
<ul>
<li><p><code>us</code> - time, given to the user </p>
</li>
<li><p><code>sy</code> - time, given to the system </p>
</li>
<li><p><code>id</code> - idle time </p>
</li>
<li><p><code>wa</code> - waiting time for input/output streams </p>
</li>
<li><p><code>st</code> - steal time </p>
</li>
</ul>
<h1 id="heading-logging">Logging</h1>
<p>Various types of processes are running in your system, like Kernel processes, daemon processes, and mother process etc. All these processes are continuously doing something in our system. And all these events are saved in a human-readable format in files known as ‘logs’. This activity of process events getting saved in files is known as ‘logging’. The logging data gets saved in the <a target="_blank" href="https://blog.gauranggaur.com/filesystem-partitions-inodes-in-linux-a-deep-dive#heading-filesystem-fs-hierarchy">‘/var’</a> directory. </p>
<h2 id="heading-how-are-logs-getting-created">How are logs getting created?</h2>
<p>This is done through a service known as ‘Syslog’. It collects all the information on whatever is happening in our system and sends it to the ‘system logger’. One of the most important components of the Syslog is a daemon process known as ‘syslogd’. This Syslog daemon waits for any event to happen and then tries to figure out what it needs to do with it. It might be possible that it needs to send the event information to a file or print that message into the console, or maybe it does not have to do anything like in the case of /dev/null (this file nullifies whatever output we send to it).  </p>
<p>System logger stores all the log files inside /var/log/syslog. But this is not the only file maintained by the System logger. There are more, like ‘/etc/rsyslog.d’. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668696690491/huxmpaO1w.png" alt="Screenshot from 2022-11-17 17-47-32.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668696892985/ZXiXLx6_8.png" alt="Screenshot from 2022-11-17 17-53-06.png" /></p>
<p>As you can see, there are files for kernel logs, mail logs, mail errors etc. And in the second file, it is maintaining <code>/var/log/ufw.log</code>. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668697183487/aH2nHXDKu.png" alt="Screenshot from 2022-11-17 17-54-46.png" /></p>
<p>If you run <code>ls /var/log</code>, you can see the list of various maintained log files. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668697509937/fV6MmVW-e.png" alt="Screenshot from 2022-11-17 18-11-02.png" /></p>
<h2 id="heading-logging-manual-messages">Logging Manual Messages</h2>
<p>You can also send messages manually into your logs. Sometimes we may have done something we want to document in the logs. Or save some keywords inside so we know after which keyword we want to start searching in the logs. We have a command for this known as <code>logger</code>. If you run <code>logger –s Hey my name is Gaurang Gaur</code> </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668697652072/d4kkTO6Nj.png" alt="Screenshot from 2022-11-17 18-06-07.png" /></p>
<p>As you can see in the last line of the <code>/var/log/syslog</code> output, this message got stored as one of the log entries. </p>
<h2 id="heading-log-management-with-logrotate">Log Management with logrotate</h2>
<p>Logging also has to manage the disk space efficiently as the log files are taking so much data. And most of the time, we want to check the latest logs instead of the 3-month-old ones. All this management can be done through the ‘logrotate’ utility. It also has a config file where we can specify and configure things, like what logs we want to keep and how we want to compress our logs. The logrotate utility runs every day through ‘cron’ or cron jobs. 
You can find logrotate in <code>/etc/logrotate.d</code>, where there is a list of various configs like bootlogs, syslogs, daemon processes etc.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668697697150/jBdGfgU5R.png" alt="Screenshot from 2022-11-17 18-27-39.png" /></p>
<p>Thanks for reading :)</p>
<p>To read the previous blogs of this Linux Series, go to <a target="_blank" href="https://blog.gauranggaur.com/">blog.gauranggaur.com</a></p>
<p>To see the video lecture of this blog, go to this <a target="_blank" href="https://www.youtube.com/watch?v=m52OeR-mfYo&amp;list=PL2kSRH_DmWVZp_cu6MMPWkgYh7GZVFS6i&amp;index=12">youtube video</a></p>
<p>Follow me on <a target="_blank" href="https://twitter.com/gaurangcodes">Twitter</a></p>
<p>Do comment your thoughts, questions or anything unique you learned below!</p>
]]></content:encoded></item><item><title><![CDATA[Boot Process, System Calls & Init Implementations in Linux For Beginners]]></title><description><![CDATA[Boot Process, BIOS, Boot Loader, Kernel, Privilege Levels & Protection Rings, System Calls, System V, Upstart, Systemd Init Implementations, Runlevels]]></description><link>https://kshitijcodes.hashnode.dev/boot-process-system-calls-init-implementations-in-linux-for-beginners</link><guid isPermaLink="true">https://kshitijcodes.hashnode.dev/boot-process-system-calls-init-implementations-in-linux-for-beginners</guid><category><![CDATA[Linux]]></category><category><![CDATA[linux for beginners]]></category><category><![CDATA[Devops]]></category><category><![CDATA[linux-basics]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Kshitij Sharma]]></dc:creator><pubDate>Tue, 15 Nov 2022 11:46:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1668512571658/dmXa3R-SC.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-boot-process">Boot Process</h1>
<p>When you start your computer, the booting of a Linux System goes through multiple stages. </p>
<h3 id="heading-bios-basic-inputoutput-system">BIOS (Basic Input/Output System)</h3>
<p>BIOS initializes the hardware and ensures it is ready by running some self-tests. It checks if the memory, hard disk, and all the connected devices are good, whether the keyboard is connected, and many other similar checks. After this, BIOS does its main job of running the bootloader. </p>
<h3 id="heading-bootloader">Bootloader</h3>
<p>The Bootloader loads the Kernel into the memory based on the Kernel parameters. In the previous <a target="_blank" href="https://blog.gauranggaur.com/">blogs</a>, we understood that different config files help configure applications and processes existing in our system. Similarly, the Kernel has some parameters based on which the bootloader would initialize its code in the memory.<br />The Grub Bootloader is the universal Linux standard and is also very efficient if you want to dual boot your system with some other OS like Windows. </p>
<h3 id="heading-kernel">Kernel</h3>
<p>Once the bootloader loads the Kernel into the memory, the third stage is the Kernel itself. The Kernel immediately initializes the memory and the devices present in the system. Then comes the main job of the Kernel, loading the ‘init’ or Mother Process.  </p>
<h3 id="heading-init-mother-process">init (Mother Process)</h3>
<p>The mother process ‘init’ starts and stops all the essential processes that run our system.  </p>
<h1 id="heading-three-levels-of-abstraction-in-linux-os">Three Levels of Abstraction in Linux OS</h1>
<p>A Linux Operating System can be classified into three levels of abstraction. </p>
<h3 id="heading-hardware">Hardware</h3>
<p>It includes CPU, memory, ports, HDD/SSD, etc. Hardware is the physical layer that computes what we do on our system.  </p>
<h3 id="heading-kernel">Kernel</h3>
<p>In the previous Linux Masterclass Series blogs, we understood that the Kernel is responsible for handling the processes, the memory management between the processes, device communication, setting up the filesystem and system calls, etc.  </p>
<h3 id="heading-user-space">User Space</h3>
<p>All screen-related things we run, like the shell, the graphics we see, the chrome browser, etc., come under the User Space level of the Operating System.  </p>
<h1 id="heading-privilege-levels">Privilege Levels</h1>
<p>The three abstraction levels we understood above also have three different privilege levels. A Kernel operates in a Kernel mode, and the User operates in User mode.  </p>
<p>In the Kernel mode, the Kernel has complete access to the hardware and controls everything in the system. On the other hand, a user mode allows access to only a small amount of safe memory and the CPU.  </p>
<p>Whenever we do anything related to the hardware, like reading/writing data and controlling network ports, we do it in the Kernel mode. And the reason behind that is simple. 
Imagine a scenario where spyware has infected your system. In such a situation, you wouldn’t want to access your hardware directly as the spyware can access your data, webcam and many other sensitive things. The two modes we talked about are also called Protection rings. Let us understand this in greater detail. </p>
<h2 id="heading-understanding-how-privilege-levels-work">Understanding how Privilege levels work</h2>
<p>Imagine there is a celebrity who is partying in a club surrounded by multiple layers of the crowd. The first layer is of the friends &amp; family that he trusts the most. The second is of their bodyguards, the third is of the club bouncers, and the last fifth layer is of the general club crowd. </p>
<p>You exist in this fifth layer, and you want to get an autograph of the celebrity or a selfie with him. To achieve this, you might need a VVIP pass, Special Permission or something like that.  </p>
<p>This is precisely how the protection rings/layers around the hardware work. The hardware is the celebrity. The layer/ring it trusts the most is the Kernel (friends &amp; family). It is the ring ‘0’. And the last layer is ring 3 of the ‘user’. If the user wants to access the hardware and its resources, the VVIP pass here is a ‘System Call’.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668510557268/uIiTPTlFd.png" alt="ls -la etc  less (6) (1).png" /></p>
<h1 id="heading-system-call">System Call</h1>
<p>System Call allows us to perform privileged instructions in the ‘Kernel mode’. The VVIP pass helps us get a similar treatment as a friend as we can talk to the celebrity, get a photo clicked etc. In the same way, a system call helps us perform some privileged instructions in the Kernel mode and then you can switch back to the User mode.  </p>
<p>System calls are also known as Syscalls. The Syscalls provide the user-space applications/processes with a way for Kernel to do something for us. They make certain services available to users through System Call API.  </p>
<p>All the System calls, like the weight system call where the Parent process wants an update on the child process termination status (Read more about it <a target="_blank" href="https://blog.gauranggaur.com/processes-in-linux-how-linux-works-internally-explained-in-detail#heading-parent-andamp-child-processes">here</a>) are just APIs that allow us to request Kernel to do something on behalf of us. </p>
<p>The Kernel offers us a fixed number of services through these APIs, and we cannot add more. Our System has a table of system calls where each has a unique ID.  </p>
<h1 id="heading-three-implementations-of-init-the-mother-process">Three Implementations of init, the mother process</h1>
<h2 id="heading-system-v">System V</h2>
<p>System V is the traditional implementation of the init process. It starts and stops processes sequentially. One of the advantages of using this implementation is that it is easier to resolve dependency issues. </p>
<p>Let us assume we have two processes: Process A and B, where B needs A to run itself. If Process A is not running, B cannot run. In such scenarios System V comes in handy as it ensures that the processes run sequentially. It will start Process A, and only then will start Process B.  </p>
<p>But there is a disadvantage of System V implementation as well. Its performance is not good. The reason is that the processes start and stop one at a time instead of parallelly/simultaneously. That hinders the performance.  </p>
<h3 id="heading-runlevels">Runlevels</h3>
<p>The status of System V is defined by ‘Runlevels’ that vary between 0 to 6.  </p>
<ul>
<li><strong>0 -&gt;</strong> Shutdown. If the system is shutting down, the runlevel will be 0. </li>
<li><strong>1 -&gt;</strong> Single User. If only a single user uses the machine, the runlevel will be 1. </li>
<li><strong>2 -&gt;</strong> Multiple users without networking. Multiple users are not connected through the network but locally.  </li>
<li><strong>3 -&gt;</strong> Multiple users with networking.  </li>
<li><strong>4 -&gt;</strong> Unused. When no one is using the system, and it is idle, the runlevel will be 4. </li>
<li><strong>5 -&gt;</strong> Multiple users with networking and GUI (Graphical User Interface). This is the state we are familiar with since we use GUI. </li>
<li><strong>6 -&gt;</strong> System is rebooting.</li>
</ul>
<p>When the system starts up, it checks what runlevel you are currently in and executes all the scripts inside that particular runlevel config.  </p>
<p>The runlevel config exists in the /etc directory. You can access it by running the command <code>ls /etc/rc</code> or if it says no such file or directory exists. Run <code>ls /etc | grep rc</code>. Here you are feeding the output of <code>ls</code> to the <code>grep</code> command and searching files starting with <code>rc</code>. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668510685590/EmpvVI6Os.png" alt="Screenshot from 2022-11-14 16-24-05.png" /></p>
<p>Now let us search the first one, <code>rc0.d</code> (runlevel 0 config) by running the command <code>ls /etc/rc0.d</code> </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668510947053/8gvQ4J0dV.png" alt="Screenshot from 2022-11-15 16-44-48.png" /></p>
<p>This is the list of all the scripts that will run at runlevel 0 or at the time of shutdown.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668511009513/skkb7wB-F.png" alt="Screenshot from 2022-11-14 16-30-31.png" /></p>
<p>This is the list of all the config scripts that will run at runlevel 5, which we are familiar with. 
Today, the System V implementation is somewhat getting replaced. But these runlevels will still be there in other implementations, as they are fundamental to how the init works and not easily replaceable. The config files we saw above are only to support those services that start and stop through the System V scripts. System V has a lot of services, and there are many commands that you can use to manage them. </p>
<p>You can run the command <code>service –status-all</code> to check the status of all the services running through the System V init scripts.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668511064017/vxjhs1mPc.png" alt="Screenshot from 2022-11-14 16-48-02.png" /></p>
<p>To change their status, you can run the command <code>sudo service [service name] [start/stop/restart]</code>. The service name can be any from the list shown above. Write <code>start</code> to start the service, <code>stop</code> to stop it, and <code>restart</code> to restart it. This command system to change the status of a service is common among all init implementations. Since Linux is still in the middle of transitioning from System V implementation, this common command style is what is helping the transition.  </p>
<h2 id="heading-upstart">Upstart</h2>
<p>Upstart was used in the earlier implementations of Ubuntu, but today Ubuntu uses the Systemd implementation. Upstart was created to improve on the System V implementation.<br />It uses an events &amp; jobs model that helps it to respond to an event as soon as it happens. Jobs are the actions it performs, and Events are the messages received from other processes that trigger the jobs. </p>
<p>To see a list of all the jobs along with their config, you can run <code>ls /etc/init</code>. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668511209339/MOnn81ucW.png" alt="Screenshot from 2022-11-15 16-49-19.png" /></p>
<p>Now let us check one of these config files and run <code>cat /etc/init/whoopsie.conf</code> </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668511299472/-8hI5W64y.png" alt="Screenshot from 2022-11-15 16-50-52.png" /></p>
<p>As you can see, Whoopsie is a crash report submission daemon. If our system crashes, this daemon process reports it. <code>start on runlevel [2345]</code> means that the system needs to start the whoopsie daemon when the runlevels are either 2, 3, 4, or 5. And <code>stop on runlevel [!2345]</code> means that the system needs to stop the whoopsie daemon when the runlevels are not 2, 3, 4, or 5. </p>
<h3 id="heading-how-does-the-upstart-implementation-work">How does the Upstart Implementation work?</h3>
<p>First, Upstart loads up all the configs from <code>/etc/init</code>. Then, when the startup event occurs, it will run all the jobs meant to be triggered by that event. The jobs that run through the startup event will trigger even more events. These events will run more jobs which might trigger even more events. So, this process keeps happening until all the jobs have run.   </p>
<h2 id="heading-systemd">Systemd</h2>
<p>Systemd is the latest, most emerging and adapted standard for init implementations. It uses goals to get your system up and running, where goals are the targets that you need to achieve. It is flexible and robust and does not do things sequentially to get the processes started.  </p>
<h3 id="heading-how-does-the-systemd-implementation-work">How does the Systemd Implementation work?</h3>
<p>It also loads up all the config files in the <code>/etc/systemd</code> and <code>/lib/systemd/system</code> directories. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668511377375/6DHY8_X_B.png" alt="Screenshot from 2022-11-14 17-40-06.png" /></p>
<p>Now let us go through the output of the second directory by running <code>ls /lib/systemd/system | less</code>. As the output will be quite long, we are using <code>less</code> with pipe (<code>|</code>). To understand less and pipe commands in deep detail with examples, click <a target="_blank" href="https://blog.gauranggaur.com/standard-streams-and-file-manipulation-in-linux-explained-in-detail#heading-how-to-use-the-pipe-to-redirect-standard-output-as-standard-input">here</a> </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668511480154/291gEzjBN.png" alt="Screenshot from 2022-11-14 17-46-40.png" /></p>
<p>You can notice that there are a lot of files ending with <code>.target</code>. Let us understand the <code>default.target</code> file. Earlier, we understood in the Upstart implementation that the startup event triggered a lot of jobs, that in return triggered a lot of events, which again triggered a lot of jobs.  </p>
<p>Now, in the Systemd init implementation, it first looks at all the configs and then all the goals it has when a system is booted. All those goals are inside the default.target file.<br />Run the command <code>cat /lib/systemd/system/default.target</code> for more information about this file. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668511531764/pEFma6eYY.png" alt="Screenshot from 2022-11-14 17-54-06.png" /></p>
<p>It first tells us that this file is a part of systemd, followed by some information on systemd. Then, it tells us what this file requires, wants, conflicts, and what happens after. In short, it has everything a system needs to do on bootup. This file says it requires a multi-user.target file. Let us check that one out by running <code>cat /lib/systemd/system/multi-user.target</code>.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668511585844/akWscRSGT.png" alt="Screenshot from 2022-11-14 18-04-12.png" /></p>
<p>Now, this file says it requires a <code>basic.target</code> file. This is how the whole process happens on boot up led by default.target. They check each other’s dependencies, load each other and make our system work.  </p>
<h3 id="heading-systemd-targets">Systemd Targets</h3>
<p>Similar to how System V has runlevels, Systemd has 'targets'.  </p>
<ul>
<li><strong>poweroff.target -&gt;</strong> As the name suggests, it is for the shutdown.  </li>
<li><strong>rescue.target -&gt;</strong> It is for a single user. </li>
<li><strong>multi-user.target -&gt;</strong> It is for multiple users with networking.  </li>
<li><strong>graphical.target -&gt;</strong> It is for multiple users with networking and GUI. </li>
<li><strong>reboot.target -&gt;</strong> It is for reboot/restart.</li>
</ul>
<p>The default.target is usually for graphical.target because GUI is the first thing we see. 
Managing Power States of the System </p>
<p>To shut down your system, you can run <code>sudo shutdown –h now</code> where the –h flag is equivalent to poweroff.  </p>
<p>To reboot the system you can run the command <code>sudo reboot</code>. It simply changes the state of the system.  </p>
<p>Since we are using the Systemd init implementation, these above two commands will be directed to the target file. And then, it will start completing those targets and their dependencies to complete the goal. That goal could be to shut down or reboot your system. </p>
<p>Thanks for reading :)</p>
<p>To read the previous blogs of this Linux Series, go to <a target="_blank" href="https://blog.gauranggaur.com/">blog.gauranggaur.com</a></p>
<p>To see the video lecture of this blog, go to this <a target="_blank" href="https://www.youtube.com/watch?v=08SwnaMhL1k&amp;list=PL2kSRH_DmWVZp_cu6MMPWkgYh7GZVFS6i&amp;index=9">youtube video</a></p>
<p>Follow me on <a target="_blank" href="https://twitter.com/gaurangcodes">Twitter</a></p>
<p>Do comment your thoughts, questions or anything unique you learned below!</p>
]]></content:encoded></item><item><title><![CDATA[Filesystem, Partitions & Inodes in Linux – A Deep Dive]]></title><description><![CDATA[Devices, Partitions, Filesystem Hierarchy, Structure and Types, Partition Table, Journaling, Inodes, Inode Table, Soft and Hard Links, Linux Internals]]></description><link>https://kshitijcodes.hashnode.dev/filesystem-partitions-inodes-in-linux-a-deep-dive</link><guid isPermaLink="true">https://kshitijcodes.hashnode.dev/filesystem-partitions-inodes-in-linux-a-deep-dive</guid><category><![CDATA[Linux]]></category><category><![CDATA[Devops]]></category><category><![CDATA[operating system]]></category><category><![CDATA[linux for beginners]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Kshitij Sharma]]></dc:creator><pubDate>Sat, 12 Nov 2022 16:27:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1668270014536/3vZG6Lc4Z.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-dev-directory-device-files">/dev Directory (Device Files)</h1>
<p>When you connect any device to your system, it needs some device drivers to function. And we need device files to exist in the /dev directory for interaction with device drivers. You can view them by running the command <code>ls /dev</code> or, for a detailed view, run <code>ls –l /dev</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668264129232/TVDF_7z3H.png" alt="Screenshot from 2022-11-10 10-43-32.png" /></p>
<p>You may notice that the standard output of this command is different from the usual <code>ls –l</code> output for any other regular directory like /home. Let us understand the unusual terminal output in the above screenshot. </p>
<h3 id="heading-permissions">Permissions</h3>
<p>A 10-bit character set makes up a Permission set for a file/directory. We understand from the previous blog of this Linux Masterclass Series that ‘d’ represents a directory, ‘-’ represents a file, and ‘l’ represents a link. You can read that part of the blog along with the ‘rgx (read-write-execute)’ and ‘ugo (user-group-others)’ dynamic <a target="_blank" href="https://blog.gauranggaur.com/user-management-and-permissions-in-linux-everything-you-need-to-know#heading-permissions">here</a> in great detail</p>
<p>But here we can see more types like b, c, and p. ‘c’ represents a character, ‘b’ represents a block, ‘s’ represents a socket and ‘p’ a pipe (<code>|</code>).  </p>
<p><strong>c -&gt; Character Device </strong></p>
<p>This device transfers data but one character at a time. As we know, every piece of information is made up of bits. And a character device transfers one bit at a time. </p>
<p><strong>b -&gt; Block Device </strong></p>
<p>This device transfers data in large fixed-size blocks. Devices like Hard Disk (HHD), and SSD are block devices. </p>
<p><strong>p -&gt; Pipe Device </strong></p>
<p>Pipe or <code>|</code> allows two processes to communicate by taking the output of one command and transferring it as an input to another. Understand this in detail <a target="_blank" href="https://blog.gauranggaur.com/standard-streams-and-file-manipulation-in-linux-explained-in-detail#heading-how-to-use-the-pipe-to-redirect-standard-output-as-standard-input">here</a> </p>
<p><strong>s -&gt; Socket Device </strong></p>
<p>This device also facilitates communication between processes like the pipe device but can communicate with multiple processes simultaneously.</p>
<h3 id="heading-number-of-hard-links">Number of Hard links</h3>
<p>It tells us how many hard links exist in this file. Discussed in much greater detail in the last section of this blog. </p>
<h3 id="heading-ownerhttpsbloggauranggaurcomuser-management-and-permissions-in-linux-everything-you-need-to-knowheading-users-and-groups"><a target="_blank" href="https://blog.gauranggaur.com/user-management-and-permissions-in-linux-everything-you-need-to-know#heading-users-and-groups">Owner</a></h3>
<h3 id="heading-grouphttpsbloggauranggaurcomuser-management-and-permissions-in-linux-everything-you-need-to-knowheading-users-and-groups"><a target="_blank" href="https://blog.gauranggaur.com/user-management-and-permissions-in-linux-everything-you-need-to-know#heading-users-and-groups">Group</a></h3>
<h3 id="heading-major-device-number-minor-device-number">Major Device Number, Minor Device Number</h3>
<p>Some of the files have only one number, and some have two separated by a comma. This differentiation of major and minor is done for the ‘Device Characterization’.  </p>
<p>The Major Device Number represents the in-use device driver of the device. For example, in the first line of the above output screenshot, <code>autofs</code> device is using the device driver <code>10</code>. And in the third line, the <code>btrfs-control</code> device uses the same one. </p>
<p>Minor Device Number tells the Kernel, what unique device it is. The kernel uses this number to differentiate between different devices. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668264242789/mKdymRsbb.png" alt="Screenshot from 2022-11-10 11-29-17.png" /></p>
<p>For example, in the above screenshot, the system has two <code>nvme</code> (one runs Windows, the other runs Linux), <code>nvme0n1</code> and <code>nvme1n1</code>. They both have the same Major Device Number <code>259</code> as they use the same drivers. But as you notice, the Minor Device Numbers are different, like <code>0</code>, <code>1</code>, <code>2</code>, <code>3</code>, <code>4</code>, <code>5</code>, <code>6</code>, and <code>7</code>. The kernel uses these unique minor device numbers to identify each one. In case you are wondering what is <code>p1</code>, <code>p2</code>, <code>p3</code>, and <code>p4</code>, they are the partitions. <code>nvme0n1</code> has 4, and <code>nvme1n1</code> has 2. </p>
<p>###Timestamp </p>
<h3 id="heading-device-name">Device Name</h3>
<p>Some devices in the above list are not connected physically to the system/motherboard. They are known as ‘Pseudo Devices’. They are <code>/dev/null</code>, <code>/dev/zero</code>, and <code>/dev/random</code>. Anything you enter/store in a ‘null’ device vanishes forever and never returns. It is like the black hole of your computer system. ‘random’ device is used to generate random numbers. All these three pseudo devices are character devices and transfer data one character at a time. </p>
<h1 id="heading-sys-directory">/sys Directory</h1>
<p>The /sys directory gives detailed information about the /dev directory. Both are similar but have some major differences. While the /dev directory allows programs to access devices, the /sys directory helps to view information and manage devices. It stores device information like model, state, hierarchy, device manufacturer, where it is plugged into the system etc. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668264297096/kjGHNvlPE.png" alt="Screenshot from 2022-11-10 12-06-23.png" /></p>
<p>The numbers inside <code>/sys/dev/block</code> are the Major and Minor Device Numbers separated by a colon. The first one is Major the other is Minor. Their colour is light blue because they are link type. If you run <code>ls –l /sys/dev/block/7:0</code>, you can see more information, related to the devices using this driver. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668264356254/zGgbN4Nnq.png" alt="Screenshot from 2022-11-10 12-10-50.png" /></p>
<h1 id="heading-filesystem-fs-hierarchy">Filesystem (fs) Hierarchy</h1>
<p>If you run the command <code>ls –l /</code> where <code>/</code> represents the root directory. It will show a detailed list of all the root folder files. The whole tree of filesystem hierarchy in the Linux System starts from this root (<code>/</code>) directory. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668264417045/-N5X7mmtL.png" alt="Screenshot from 2022-11-10 13-51-42.png" /></p>
<p>This list also consists of /sys and /dev we understood above. Let us understand the other important directories and files in this root folder. </p>
<ul>
<li><p><strong>bin directory -&gt;</strong> It contains essential and ready-to-run binaries for commands like mkdir, ls, cd, and many more like mongod, mongoose etc. </p>
</li>
<li><p><strong>boot directory -&gt;</strong> It contains the bootloader files used by the Kernel. </p>
</li>
<li><p><strong>dev directory -&gt;</strong> It contains the device files </p>
</li>
<li><p><strong>etc directory -&gt;</strong> It is the core system config directory. It contains all the configuration files of any program you run. Most programs you run have configurations/settings that you can influence to change their functioning. </p>
</li>
<li><p><strong>home directory -&gt;</strong> it is the personal directory of the user. This is where your general-purpose directories are like Desktop, Documents, Downloads, Pictures etc. And the location where the terminal opens up by default. </p>
</li>
<li><p><strong>lib directory -&gt;</strong> It contains the library files that the binaries might use. Binaries of the commands might need some external libraries to execute their code, like in web development. </p>
</li>
<li><p><strong>media directory -&gt;</strong> It is an attachment point for any USB or something like that. If you connect a USB to the system, this is where it gets connected and accessed.  </p>
</li>
<li><p><strong>mnt directory -&gt;</strong> It is the temporarily mounted filesystem. The entire filesystem gets temporarily mounted here. </p>
</li>
<li><p><strong>opt directory -&gt;</strong> It contains optional software packages. For example, if you are using Google Chrome, you will find its name inside it if you run the command <code>ls /opt</code> </p>
</li>
<li><p><strong>proc directory -&gt;</strong> It contains the Process information. You can understand it in much greater detail <a target="_blank" href="https://blog.gauranggaur.com/processes-in-linux-how-linux-works-internally-explained-in-detail#heading-how-everything-in-linux-is-a-file-the-proc-directory">here</a> </p>
</li>
<li><p><strong>root directory -&gt;</strong> It is like a home directory for the root user just like ‘/home’ is for a regular user. </p>
</li>
<li><p><strong>run directory -&gt;</strong> It contains information about the running system since boot. From the moment you start your system, whatever information the system collects gets stored in this /run directory. </p>
</li>
<li><p><strong>sbin directory -&gt;</strong> It contains the system binaries. The earlier binaries directory was for commands that any user could run. But the system binaries can only be executed by the root user. </p>
</li>
<li><p><strong>sys directory -&gt;</strong> It helps in managing the filesystem. </p>
</li>
<li><p><strong>tmp directory -&gt;</strong> It is the storage for temporary files. </p>
</li>
<li><p><strong>usr directory -&gt;</strong> It contains the user-installed software and utility. </p>
</li>
<li><p><strong>var directory -&gt;</strong> var stands for Variable. Any system login, user tracking, caches, and many other constantly changing things are variables maintained in this variable directory. </p>
</li>
</ul>
<h1 id="heading-filesystem-fs-types">Filesystem (fs) Types</h1>
<p>There are different implementations of filesystems. Some are faster than others, and some support larger storage. Different filesystems have different ways of structuring their data. The structure we see in the above section of the root directory is not the same for every system. It might be different based on the requirements.  </p>
<p>Let us say we have an app that runs on a filesystem. The app doubts whether the filesystem supports the way it runs. In such a situation, we can take the help of an abstraction layer between the app and the filesystem known as a ‘Virtual File System’. If the app wants to operate on this filesystem, it will try to use the Virtual File System. Now, it is the job of the Virtual File System to ensure that the app file is operable on the filesystem, no matter the structure. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668265755776/gxhGKN5u2.png" alt="ls -la etc  less (3) (1).png" /></p>
<p>You can have multiple filesystems in your computer machine depending on how you have created the partition. We saw in the above section that there were two partitions<code>nvme0n1</code> and <code>nvme1n1</code>, one for Windows and the other for Linux. </p>
<h1 id="heading-journaling">Journaling</h1>
<p>Let us say you have a large file and are copying it from one place to another. Since this is a large file, it will take a lot of time for copying to finish. Suppose the system battery gets depleted or your system shuts down for some reason, and the large file you tried to copy, gets corrupted. Because of this, there will be inconsistency in the filesystem. When you restart your system, it will perform some filesystem checks to make sure everything is okay.  </p>
<p>You might have noticed when your computer unexpectedly shuts down takes a lot of time to boot back up on restart. Filesystem checks are one of the reasons why.  </p>
<p>A process known as ‘Journaling’ helps you avoid such situations. It is part of the majority of operating systems that come these days. With Journaling, before your system begins to copy a file, it will write down what the user is attempting in a log file. This log file is known as a ‘Journal’. Once the task gets completed, like copying a file, it will be marked as ‘completed’ in the journal. </p>
<p>With the Journaling feature, your filesystem remains consistent. And if suddenly your system shuts down, it would know what it was trying to do before powering off by checking the journal. It results in the boot-up being much faster. </p>
<h1 id="heading-desktop-filesystem-types">Desktop Filesystem Types</h1>
<ul>
<li><strong>ext4 –&gt;</strong> This is one of the latest versions of Linux Filesystem and is compatible with previous filesystems like ext3, ext2 etc. It supports disk space of up to 1 exabyte and a file size of up to 16 terabytes. ext4 is the standard choice for a Linux Filesystem. </li>
</ul>
<blockquote>
<p>For Reference </p>
<p>8 bits -&gt; 1 byte </p>
<p>1024 bytes -&gt; 1 kb </p>
<p>1024 kb -&gt; 1 Megabyte </p>
<p>1024 Mb -&gt; 1 Gigabyte </p>
<p>1024 Gb -&gt; 1 Terabyte </p>
<p>1024 Tb -&gt; 1 Petabyte </p>
<p>1024 Pb -&gt; 1 Exa byte </p>
<p>1024 Eb -&gt; 1 Zeta byte </p>
<p>1024 Zb -&gt; 1 Yota byte </p>
<p>1024 Yb -&gt; 1 Bronto byte </p>
<p>1024 Bb -&gt; 1 Geop byte </p>
</blockquote>
<ul>
<li><p><strong>Btrfs or Butter/Better File System -&gt;</strong> This is also one of the latest Linux filesystems and comes with many things like snapshots, incremental backups, and performances. It is a new filesystem and yet not stable.  </p>
</li>
<li><p><strong>XFS –&gt;</strong> It is a high-performance journaling filesystem. It is generally good for servers that host media like YouTube and Netflix. </p>
</li>
<li><p><strong>NTFS &amp; FAT –&gt;</strong> It is used by the Windows Operating System. </p>
</li>
<li><p><strong>HFS+ -&gt;</strong> It is used by the macOS. </p>
</li>
</ul>
<p>You can check what all filesystems your computer system uses by running the command <code>df –T</code>, where the T flag displays a column with filesystem type. </p>
<h1 id="heading-partition-table">Partition Table</h1>
<p>We already know from the above sections that the HDD and SSD are block devices. And we can create partitions inside the block devices to separate data. Instead of having one filesystem in the entire HDD, SSD or nvme, you can create multiple partitions that act as individual block devices. This process will let you have more than one filesystem. </p>
<p>For example, in your 1 Tb SSD, you can have two 500 Gb partitions, one where Windows is running and the other for Linux. If we have some space that is not a part of any partition is declared as Free Space. </p>
<p>To check what partitions you have created, you can check the ‘Partition Table’. It also tells where the partition begins and ends, which are bootable, and which sector we have allocated to a partition etc.  </p>
<p>There are two Partition Schemes: </p>
<ol>
<li><p>MBR or Master Boot Record </p>
</li>
<li><p>GPT or GUID Partition Table </p>
</li>
</ol>
<h2 id="heading-mbr">MBR</h2>
<p>MBR is the traditional partition table that used to be the standard early on. It only supports disks up to 2 Tb. The problem with MBR is that it has a limit of four partitions known as ‘Primary Partitions’. But you can opt to have only one partition and make it an ‘Extended Partition’. 
In this Extended Partition, you can create as many ‘Logical Partitions’ as you want that behave as Primary partitions. But you can only choose one Primary partition to extend.</p>
<h2 id="heading-gpt">GPT</h2>
<p>GPT is becoming the new standard for disk partitioning. Unlike MBR, GPT only has one partition type, and you can divide it as much as you want. Each partition will have a Globally Unique ID (GUID). GPT is used with UEFI-based Booting.  </p>
<h1 id="heading-filesystem-structure">Filesystem Structure</h1>
<p>A filesystem is an organized collection of files and directories. It’s like a database to manage the files and the actual files themselves. Any Filesystem Structure has four major components:  </p>
<ul>
<li><p><strong>Boot Block –</strong> It is in the first few sectors of the filesystem. It is only used to boot the Operating System. </p>
</li>
<li><p><strong>Super Block –</strong> It is the single block that comes after the boot block and generally contains the information about the filesystem itself. Information like the size of the Inode tables, filesystem etc.  </p>
</li>
<li><p><strong>Inode Table –</strong> It is like a database that manages our files. Each file or directory has a unique entry in the Inode table that contains information about them.  </p>
</li>
<li><p><strong>Data Blocks –</strong> These blocks contain the actual data of the files and directories.<br />We can run the command <code>sudo parted –l</code> to view the partition detail of a system.  </p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668264483243/0Q3HJ76RM.png" alt="Screenshot from 2022-11-10 17-23-57.png" /></p>
<p>As you can see, Partition Table is ‘gbt’ which I explained earlier. Inside the table, the first one is for the Boot Block, which starts at 1024kb and ends at 538MB. The second part is the Data Block dedicated to the Linux OS with an ext4 filesystem. </p>
<p>There are different disk partitioning tools you can use: </p>
<ul>
<li><p><strong>fdisk –</strong> It is a CLI-based tool, and it does not support GPT.  </p>
</li>
<li><p><strong>parted –</strong> It is also a CLI-based tool. It supports both MBR and GPT. </p>
</li>
<li><p><strong>Gparted –</strong> This is the GUI-based version of parted. </p>
</li>
<li><p><strong>gdisk –</strong> It is also CLI-based and does not support MBR. </p>
</li>
</ul>
<h1 id="heading-etcfstab-file">/etc/fstab File</h1>
<p>If you want automatic mounting of a filesystem at system startup, you can add it inside this /etc/fstab file. You cannot read or go through a filesystem without mounting it to the system. For example, Linux is mounted in the system, and that is how I am able to use it on the machine. Earlier, we saw the ‘mnt’ directory, which is the place where this Linux OS is mounted. </p>
<p>If you run <code>cat /etc/fstab</code>, it will show a bunch of information. Let us go through some data points inside it.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668264543724/wDYoifUXv.png" alt="Screenshot from 2022-11-11 11-22-48.png" /></p>
<p>It is showing <code>UUID=4b6264c6-9bea-42a9-8f11-956f53700ea7</code>. It is the unique identifier for the Linux Filesystem. In front of it, there is the directory <code>/</code> (root), where the Linux Filesystem is mounted. Then, there is the Filesystem type <code>ext4</code>. Then, we have the mount options, followed by dump and pass columns. We use the dump utility to create a backup. Pass system means in what order your filesystem should be checked, in case some discrepancy occurs.  </p>
<p>The last line mentions /swapfile and swap. Let us understand them. </p>
<h1 id="heading-swap-memory">Swap Memory</h1>
<p>We use swap to assign some virtual memory to your system. If you are low on memory or have a low amount of RAM, you can create a Swap Partition. The system uses this swap partition to swap memory pieces of idle processes to the disk.  </p>
<p>The system takes out some pieces of memory that some idle processes occupy in the RAM and saves them into the swap partition inside the disk. This process will free up some memory in your system to be used by the active processes. </p>
<h1 id="heading-disk-free-and-disk-usage-df-h-and-du-h-commands">Disk Free and Disk Usage (‘df –h’ and ‘du –h’ Commands)</h1>
<p>If you run the command <code>df –h</code> where the h flag shows a human-readable version of the output, it will show the currently mounted filesystems utilization. It includes their size, usage, availability, use percentage, and where we have mounted the filesystem in the machine. For example, the Linux filesystem is <code>/dev/sda2</code> in the third row with a size of 916 Gb and mounted in the <code>/</code> (root) directory. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668264662273/5PUaUYgRd.png" alt="Screenshot from 2022-11-11 12-17-09.png" /></p>
<p>If you want to see what is taking how much space in your whole system, you can run the command <code>du –h</code>.  </p>
<h1 id="heading-inode-table">Inode Table</h1>
<p>In the Filesystem Structure section, I explained that Inode Tables are like a database to manage files. In this table, each file/directory has an ‘Inode’ that stores all the information about it.  </p>
<p>That information can be like file type, owner, group, permissions, number of hard links, size, number of blocks allocated, and the pointers to data blocks of the file. It is everything except the filename and the file itself. Because a file is stored on the disk and not in the inode table.  </p>
<p>When we create a filesystem, some space for Inodes is allocated as well. There is an algorithm that determines how much inode space would be needed based on the size of the disk. You might be familiar with the error that says, ‘You are out of disk space’, but when you check your disk usage, you notice that there is still a good chunk of it left. It means your disk has space but the space allocated for your inode table does not have space anymore.  </p>
<p>Data Storage on our disks depends on both, the data and the database (Inode Table). If you run the command <code>df -i</code>, it will show the total inodes available for each filesystem, how many you have used, how many are free, and the usage percentage. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668264875485/cN14WYyYC.png" alt="Screenshot from 2022-11-11 13-23-38.png" /></p>
<p>Now, let us assume that you created the total number of empty files &amp; directories equal to the available inodes for the Linux filesystem. Now even if the files are empty and your disk usage is not filled, you still would not be able to create/download any more files and directories in your system. Because there would be no space left in the inode table to add more entries for any new files/directories.  </p>
<h2 id="heading-inode-information">Inode Information</h2>
<p>We identify Inodes by numbers. Whenever a new file/directory gets created, they are assigned an inode number. Inode numbers are usually in sequential order, but sometimes you may get a lower inode number. Because when you delete a file/directory, the associated inode number gets freed. And when you create a new file/directory, it may get assigned the same free inode number.  </p>
<p>You can check the inode number of any file/directory by running the <code>ls –li</code> command. The first column consists of uniquely assigned inode numbers. To see a more detailed view of a directory, you can use the command <code>stat [directory name or path]</code>. </p>
<p>If I run <code>stat /</code>, it will show me the information of my root directory. It consists of the size, Blocks, UID, GID, Access (permissions) in both numerical and graphical form, type (which is directory), Inode number, number of links, and some timestamps.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668264952035/9j6ZzUsH_.png" alt="Screenshot from 2022-11-11 13-53-21.png" /></p>
<h2 id="heading-how-does-an-inode-locate-a-file">How does an Inode locate a file?</h2>
<p>Let’s understand this with an example. You created two files: ‘First name’ and ‘Last name’. You created the variable ‘Elon’ in the ‘First Name’ file that gets stored in block 1 of main Data Storage. Then, you created the variable ‘Musk’ inside the ‘Last Name’ file that gets stored in block 2 of Data Storage. Then, you created the variable ‘Mark’ in the ‘First Name’ file that gets stored in block 3 of storage. Then, you created the variable ‘Cuban’ in the ‘Last Name’ file that gets stored in block 4 of storage. </p>
<p>Now, Blocks 1 &amp; 3 belong to the ‘First Name’ file and Blocks 2 &amp; 4 belong to the ‘Last Name’ file. You can notice that the files’ data is not stored sequentially. We know this data is stored somewhere in the Data Storage, but we don’t exactly know where it is as it was not stored sequentially. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668266947245/xKuInrth2.png" alt="ls -la etc  less (4) (1).png" /></p>
<p>In such a situation, Inodes help in finding the desired data. Each Inode contains 15 pointers. This set of 15-pointers is also known as a ‘Super Block’ which I explained above in the Filesystem Structure section. Each Inode pointer or block out of 15 has a size of 4 kb. The first 12 pointers point directly to the data blocks of the file. For the ‘First Name’ file, the pointers will point to the 1st &amp; 3rd data block and for the ‘Last Name’ file, the pointers will point to the 2nd &amp; 4th data blocks.  </p>
<p>But if a single Inode pointer is 4 kb, does that mean a single Inode can only contain 48 kb of max data? The answer is no. This is when the 13th, 14th, and 15th blocks/pointers of an Inode come into the picture. They can point to a group of pointers (an Inode). And let’s say that Inode will again point to another Inode that at last points to a comparatively much larger number of data blocks compared to 15. </p>
<p>For example, Inode A’s 13, 14, and 15 Pointers point to three different Inodes. Those three Inodes’ 13, 14, and 15 pointers point further to three different Inodes. This is how a single initial Inode can point to a much larger number of data blocks.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668269617120/SBKSzKWL8.png" alt="ls -la etc  less (5).png" /></p>
<p>Earlier I told you that an ext4 filesystem has 1 exabyte of disk space and 16 terabytes of file space. The vast network of Inodes we saw above fills this 16 TB of file space. In other words, this network of pointers pointing to other Inodes can go to a maximum size of 16 TB.<br />All the Inodes that come between the first initial Inode and the data are known as ‘Indirect Blocks’.  </p>
<h1 id="heading-links">Links</h1>
<h2 id="heading-symlinkssoft-links">Symlinks/Soft Links</h2>
<p>If you have used Windows OS, you might be familiar with shortcuts. When we install a file, Windows asks us that do we want a shortcut for this file on the Desktop. These shortcuts are Aliases of the directory/file/program that we are shortcutting at a particular location (like, Desktop).  </p>
<p>If you make some changes or delete the original file/directory, it will affect the shortcut as well and might break it. If the original file ceases to exist, where will the shortcut lead to?<br />In Linux, Symlinks/Symbolic Links/Soft Links are equal to shortcuts in Windows. To create a soft link of a file, you can run the command <code>ln –s [filename] [SoftLink name]</code>. Here <code>ln</code> stands for a link, and the <code>-s</code> flag stands for a soft link.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668265017087/5REcVIeER.png" alt="Screenshot from 2022-11-11 16-40-26.png" /></p>
<p>As you can see, there is one more file created. It is a soft link and is pointing towards the test1 file. And in the permissions column, instead of <code>-</code>, it has <code>l</code>, which means it is a link type. To understand Permissions in deep detail, go <a target="_blank" href="https://blog.gauranggaur.com/user-management-and-permissions-in-linux-everything-you-need-to-know#heading-permissions">here</a> </p>
<h2 id="heading-hard-links">Hard Links</h2>
<p>To create a hard link, you only have to remove the <code>-s</code> flag from the above command. Run a command like <code>ln test2 hard2</code> to create a hard link.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668265064622/VuHGSXv5I.png" alt="Screenshot from 2022-11-11 17-02-04.png" /></p>
<p>You can notice that earlier, the number column after the Permission column consisted of only the digit ‘1’, but now test2 and hard2 have ‘2’ in their rows. Because this column tells us how many hard links of an Inode number exist in the system. Now that we have created a hard link of the ‘test2’ file, the number to ‘2’ from ‘1’.  </p>
<p>Notice that the Inode number of hard2 and test2 is the same, contrary to soft1 and test1, which have unique Inode numbers. But earlier, we learned that each file/directory we create should have a unique Inode number. Let us understand what is happening here. </p>
<p>There is an Inode number and a file point to it. If we now create a soft link, it will point to the file instead of the Inode number. But if we create a Hard link, it points directly to the same Inode number the file is pointing to. If this file gets deleted, the soft link will also stop working. But since the hard link is pointing directly to the Inode, it will still work.  </p>
<p>It does not mean that if you make any changes to the original file, they will not reflect in the hard link. They will. As the changes are made in the data storage. And both the file and hard link are pointing to the same data storage blocks via Inode. </p>
<blockquote>
<p>If you make any changes to the soft link file, they will reflect in the original file as well. </p>
<p>If you make any changes in the hard link file, they will reflect in both the original file and the soft link file.</p>
<p>If you delete the original file, then the soft link file will not work, but the hard link file will work properly.  </p>
</blockquote>
<p>Thanks for reading :)</p>
<p>To read the previous blogs of this Linux Series, go to <a target="_blank" href="https://blog.gauranggaur.com/">blog.gauranggaur.com</a></p>
<p>To see the video lecture of this blog, go to this <a target="_blank" href="https://www.youtube.com/watch?v=PbMT53jaUaU&amp;list=PL2kSRH_DmWVZp_cu6MMPWkgYh7GZVFS6i&amp;index=9">youtube video</a></p>
<p>Follow me on <a target="_blank" href="https://twitter.com/gaurangcodes">Twitter</a></p>
<p>Do comment your thoughts, questions or anything unique you learned below!</p>
]]></content:encoded></item><item><title><![CDATA[Processes In Linux - How Linux Works Internally? Explained in Detail]]></title><description><![CDATA[Understanding Linux Processes in Detail. Management of Process. Parent, Child, Orphan, Zombie and Mother Process. Termination. Signal. CPU Time. Jobs]]></description><link>https://kshitijcodes.hashnode.dev/processes-in-linux-how-linux-works-internally-explained-in-detail</link><guid isPermaLink="true">https://kshitijcodes.hashnode.dev/processes-in-linux-how-linux-works-internally-explained-in-detail</guid><category><![CDATA[Linux]]></category><category><![CDATA[linux for beginners]]></category><category><![CDATA[operating system]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Devops]]></category><dc:creator><![CDATA[Kshitij Sharma]]></dc:creator><pubDate>Wed, 09 Nov 2022 10:44:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1667990396452/XnNV-j0QY.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Processes are programs running on your Linux system, managed by the Kernel. Each Process has a PID (Process ID) associated with it used by the Kernel to identify it. If we execute the command <code>ps</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667987409700/FP0y6lGg7.png" alt="Screenshot from 2022-11-04 16-03-34.png" /></p>
<p>The terminal shows us four columns.</p>
<ul>
<li><p>PID - Process ID</p>
</li>
<li><p>TTY – 'Controlling Terminal' of the process. Most Processes we run are associated with a terminal. The ID of that terminal is written in the TTY. </p>
</li>
<li><p>TIME – Total CPU Usage Time a Process is taking </p>
</li>
<li><p>CMD – CMD (Command) is the name of the executable command/program currently running in the system.</p>
</li>
</ul>
<p>If you open another terminal window while the first one is still open and run the <code>ps</code> command, the TTY value will change from 0 to 1. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667987462077/qxLxT-oJA.png" alt="Screenshot from 2022-11-07 17-02-57.png" /></p>
<h1 id="heading-ps-aux-command">ps aux command</h1>
<p>In the <code>ps aux</code> command, a, u, and x are the flags of the ‘ps’ command.  </p>
<ul>
<li>a – All the processes, even the ones run by other users </li>
<li>u – More details about the processes </li>
<li>x – All the processes, even the ones running in the background with no associated terminal (TTY).</li>
</ul>
<p>If you run the <code>ps aux</code> command, it opens a large output with more rows and columns. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667987517348/3C7es3ttD.png" alt="Screenshot from 2022-11-07 17-05-15.png" /></p>
<ul>
<li>USER – Every Process has an owner. </li>
<li>PID – Process ID. </li>
<li>%CPU – Percentage of CPU time a Process is taking. </li>
<li>%MEM – Percentage of Memory a process takes out of the entire physical memory of the system. </li>
<li>VSZ – When a Process starts up, Virtual Memory Usage or VSZ is the maximum memory in kb available to the entire Process. It can use some portion or all of the allocated memory but not more.</li>
<li>RSS – The amount of memory in kb currently used by the process out of the total VSZ. </li>
<li>TTY – Earlier, we saw the TTY column only consisted of values like ‘pts/o’ or ‘pts/1’, but now it also has ‘?’, ‘tty2’, and ‘tty3’ as the values. ‘?’ means no terminal associated. We’ll understand the other values below in the Controlling Terminal section. </li>
<li>STAT – This tells us the process status. </li>
<li>START – The exact time a process started. </li>
<li>TIME – Total CPU Usage Time a process is taking. </li>
<li>CMD – Name of the command/program.</li>
</ul>
<h1 id="heading-top-command">top command</h1>
<p>If you run the <code>top</code> command, this will show the real-time version of the <code>ps aux</code> data and much more. Here the values keep fluctuating based on what happens in the system. Press <code>q</code> to get back to the terminal. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667987627785/qecnszNsn.png" alt="Screenshot from 2022-11-07 18-06-36.png" /></p>
<p>The <code>top</code> command helps us to find out what processes might be slowing down or affecting the system in any other way. </p>
<h1 id="heading-controlling-terminal-terminal-and-pseudo-terminal">Controlling Terminal (terminal and pseudo-terminal)</h1>
<p>Earlier in the TTY section of <code>ps aux</code>, we saw two types of values. </p>
<p>Tty1, tty2 or tty3 – Regular Terminal </p>
<p>pts/0 or pts/1 - Pseudo Terminal </p>
<p>A regular Terminal is a terminal that has no graphics associated with it. It is only a shell where you can only use a keyboard to type commands without any GUI elements. Type ‘Ctrl+Alt+F3' to access TTY3, and to exit type ‘Alt+left arrow’. </p>
<p>The processes not associated with any terminal and run without it are known as Daemon Processes. They start when the system boots up and terminate when it shuts down. The daemon processes run in the background, ensuring our system runs fine. We do not want them to close, as our system might crash without them. That is the reason they are not associated with a controlling terminal.  </p>
<p>All the processes in the <code>ps aux</code> output with ‘?’ under the TTY column are essential processes without any associated terminal. Because if we accidentally close a terminal that is running one of them, our system will crash. </p>
<h1 id="heading-processes-are-an-instance-of-a-program">Processes are an instance of a Program</h1>
<p>Open three terminals and execute the<code>cat</code> command in two of them with or without an argument. And in the third one, execute <code>ps aux | grep cat</code> where you are transferring the output of <code>ps aux</code> to the <code>grep</code> command that will search the input for ‘cat’ and show output in the terminal with all the lines that contain ‘cat’. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667987753427/envt32pZR.png" alt="Screenshot from 2022-11-08 13-46-52.png" /></p>
<p>Notice that there are two instances of <code>cat</code>, one running in <code>pts/1</code> and the other in <code>pts/2</code>. Although both terminals execute the same command or program, we still have two instances. If you close the other two terminals, there will be no instances of <code>cat</code> running in pseudo-terminals anymore. This example proves that ‘processes’ are instances of a running program. We can have as many instances of a program in our system as we want. </p>
<h1 id="heading-who-manages-the-processes-and-how">Who manages the Processes? And how?</h1>
<p>By managing, I mean who reserves/allocates and makes decisions about the VSZ memory, CPU time etc., for a process to use. The answer is the ‘Kernel’. The Kernel manages all the processes in the system. It loads up the code of a program in the memory, allocates all the resources that the process might need, and keeps all of them in check. It knows the status, the owner, and the resources allocated/consumed by a process. </p>
<p>When a process ends, the Kernel freezes up the resources the process was using and makes them available for other processes to use. </p>
<p>Now let us come to the How part. When the user creates an instance of a program, it clones using the ‘Fork System Call’. Fork System Call creates an identical child process (or we can say, forks it) and assigns a Process ID (PID) to it. The original process that this child process was cloned or forked from becomes the Parent Process. </p>
<h1 id="heading-parent-andamp-child-processes">Parent &amp; Child Processes</h1>
<p>A Child Process can use the same ‘Program’ that its parent process was using or in most cases, it can use ‘execve system call’ through which it can run a new program.
If you run the command <code>ps –l</code>, it shows a more detailed view of the <code>ps</code> command output where there is a new column called <code>PPID</code>. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667987849194/lwku7oOX9.png" alt="Screenshot from 2022-11-08 14-20-46.png" /></p>
<p>The <code>ps</code> command has a personal ‘PID’ of 13087 and a ‘PPID’ of 11530. This PPID of 11530 is the same as PID 11530 of the <code>bash</code> command. So, we can say the ‘ps’ command process is the child process of the ‘bash’ command. But you can see the ‘bash’ command also has a PPID, which means it also has a parent process. We can find it out by running <code>ps aux | grep 11522</code> where 11522 is the PPID of bash. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667987936614/rUoq-ACBr.png" alt="Screenshot from 2022-11-08 14-26-06.png" /></p>
<p>We can see that <code>bash</code> is the child process of <code>/usr/libexec/gnome-terminal-server</code>.  </p>
<h1 id="heading-mother-process">Mother Process</h1>
<p>Now, you may wonder if every process is the child of its parent process, then there must be a process above all other processes, the Mother process. This Mother Process is known as ‘init’. When the system boots up, it creates the mother process ‘init’ with the PID of 1. ‘init’ runs on root privileges with the ‘root’ user as the owner and is responsible for most of the processes responsible for running the system. </p>
<p>By running the <code>ps aux</code> command, the first line shows the ‘init’ process with the PID of 1 and owner as ‘root’. It has the highest ‘VSZ’ allocated and ‘RSS’ used. All the other processes below, with TTY as ‘?’ and PIDs consecutively increasing, are the Daemon Processes essential for running the system. They are all child processes or forks of the ‘init’ mother process. </p>
<h1 id="heading-termination-of-a-process">Termination of a Process</h1>
<p>The system terminates a Process using the ‘-exit system call’. It is responsible for freeing up all the utilized resources. When a process terminates, it lets the kernel know why it is terminating with a ‘Termination Status’. The most common Termination status is ‘0’, which means ‘the process succeeded’.  </p>
<p>When a child process terminates, its parent process has to acknowledge its status with the ‘wait system call’ and issue the termination status. </p>
<p>There are different use cases when it comes to the termination of a process. Let us understand them. </p>
<h2 id="heading-orphan-process">Orphan Process</h2>
<p>In this case, the parent process gets terminated instead of the children. These Child Processes are known as Orphan Processes. They do not have a Parent Process that can use the ‘wait system call’ to acknowledge the termination of their child. In such a case, the Kernel puts such Orphan Processes under the control of the ‘init’ mother process. </p>
<h2 id="heading-zombie-process">Zombie Process</h2>
<p>In this case, the parent process exists but does not acknowledge the termination of the child process and does not call the ‘wait system call’ for some reason. So, the Kernel turns such a Child Process into a ‘Zombie Process’. It is living dead, meaning it is terminated, but still exists because the system does not know its termination status. </p>
<p>Let us assume after the child process turns into a zombie process, the Parent process calls the ‘wait system call’. This is known as ‘reaping’. But if the ‘reaping’ does not happen, the ‘init’ process adopts the zombie process, calls the ‘wait system call’ and issues a termination status so the zombie process can rest in peace. </p>
<h1 id="heading-signal">Signal</h1>
<p>A Signal is a notification sent to a Process that something has happened. When a user kills or suspends a process, the process needs to know that it has been killed/suspended only then the user action will transpire. Maybe some hardware or software issue occurred, and the Kernel wants to notify the Process. All this happens with the help of signals. </p>
<p>There are many things a Process can do with a signal it receives. It can ignore the signal or catch it and perform a signal handler routine based on the configuration. All processes have signal handlers that are responsible for handling different signals. </p>
<p>For example, the software is running and as soon as it receives a termination signal saying it has to stop working and terminate itself, the signal handler will save the collected data and terminate the process. There are different types of signals: </p>
<ul>
<li>SIGHUP/HUP/1 – Hang up </li>
<li>SIGINT/INT/2 – Interrupt </li>
<li>SIGKILL/KILL/9 – Kill. No Signal Handler of any process can block this signal.</li>
<li>SIGSEGV/SEGV/11 – Segmentation Fault </li>
<li>SIGTERM/TERM/15 – Terminate </li>
<li>SIGSTOP/STOP/19 - Stop</li>
</ul>
<p>If you run the command <code>kill 15345</code> where 15345 is the PID, it will terminate the process. And the ‘exit system call’ will be called to free up all the occupied resources in the system. But let us say you do not want to terminate but kill the process entirely. </p>
<p>You can run the command <code>kill –9 15345</code> where 9 is the numerical representation of the KILL signal. It will destroy the process instantaneously, but the occupied resources might not free up, which the Kernel might have to do later. </p>
<p>SIGHUP Signal is sent when the terminal on which the process was running is closed. In simple words, it tells the Process that you do not have any medium to work anymore as your terminal is closed, and you can hang up. </p>
<p>SIGINT Signal is sent to terminate/interrupt the Process when we press Ctrl+C after running the command. </p>
<p>SIGSEGV Signal occurs when the process tries to access some area of the memory it does not have access to. For example, We run the command <code>cat /etc/shadow</code>, but as we know that it is a root file and the user does not have access to it, this is when the segmentation fault occurs. </p>
<p>SIGTERM Signal kills the Process but after doing the cleanup like freeing the allocated memory etc., unlike SIGKILL. </p>
<p>SIGSTOP Signal only suspends a process for some time after which the process might resume. </p>
<h1 id="heading-cpu-time">CPU Time</h1>
<p>We generally run multiple software in our system simultaneously like, Chrome, Terminals, VSCode etc. It may seem like all are running simultaneously, but that is not the case. All the processes use the CPU for a small amount of time, known as a ‘Time Slice’. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667988927925/ZsM94Dq_t.png" alt="ls -la etc  less (2).png" /></p>
<p>All the Processes use a short amount of CPU time (time slice in milliseconds) one by one in a cycle. Once a process gets its time slice, it usually pauses for a few milliseconds allowing other processes to use that freed CPU time slot.  </p>
<p>This is where the number of cores in the CPU plays a role. A CPU can be dual-core (2), quad-core (4), octa-core (8) etc. The more cores a CPU has, the more Processes it can run simultaneously. For example, if your CPU has four cores and runs 100 Processes, each core in the system handles 25 processes. </p>
<p>The Kernel handles this switching of CPU time among the Processes. If a process gets this control, it will tend to keep a disproportionate amount of CPU time. We have a way to influence the amount of CPU time a process can have with a value known as ‘nice’. 
nice and renice commands </p>
<p>All the Processes running in the system have a number to determine their priority for the CPU for the amount of time slice the CPU should give them.  </p>
<p>When you run the command <code>top</code>, there is a column ‘NI’ which contains values like 0, -20, 19, and 5. The higher the value, the nicer the process is. </p>
<p>High NI Value -&gt; Low Priority </p>
<p>Low NI Value -&gt; High Priority </p>
<p>If a process has a Low NI Value means it is not very nice. So, the CPU has to give more time to run that process smoothly and keep it on high priority. On the other hand, if a process has a High NI Value, the CPU does not have to prioritize it as the process is already very nice and will run smoothly even on a thin Time Slice.  </p>
<p>You can change this NI Value with the command <code>nice</code>. For example, if there is a process that is not nice and you want the CPU to keep it on High Priority and a lot more of its time to run it faster, you can do that by running the command <code>nice –n –50 [process name]</code>.  </p>
<p>For the processes already running on the system, you can use the command <code>renice</code> like <code>renice –10 –p [PID]</code> where PID is of the already running process, and you want to change its NI value. </p>
<p>#States of a Process </p>
<ul>
<li>R State – Running or Runnable. It means the process is running or is waiting for the CPU to give it time to process. </li>
<li>S State – Interruptible Sleep. It means the process is waiting for some event which can be input from the user. </li>
<li>D State – Uninterruptible Sleep. It means the process cannot be killed or interrupted by a signal. The only way to do it is to reboot your system. </li>
<li>Z State – Zombie State. It means the process is terminated and waiting for their ‘wait call status’ to be collected. We understood this in the above ‘Termination of a Process’ section. </li>
<li>T State – Stopped State.</li>
</ul>
<h1 id="heading-how-everything-in-linux-is-a-file-the-proc-directory">How everything in Linux is a file - the ‘/proc’ directory</h1>
<p>In the first blog of this Linux Masterclass series, we talked about how everything, even the commands, processes, and directories, are all files in the Linux system. </p>
<p>‘/proc’ is the directory that contains all the information about all the processes in the system. If you run the command <code>ls /proc</code>, it will show a large list of the same. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667989101698/KqlM_JWfc.png" alt="Screenshot from 2022-11-08 18-09-06.png" /></p>
<p>All the subdirectories of this /proc directory in the output above are all the processes running in the system. Most of their names are their respective PIDs (Process IDs). These subdirectories contain all the information related to these specific processes.</p>
<p>If you run `ls /proc/1', the first subdirectory in the output which belongs to the ‘init’ mother process will show up.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667989228277/eqEDAcovJ.png" alt="Screenshot from 2022-11-08 18-19-52.png" /></p>
<p>Three of the results we are not permitted to see as they belong to the root. All these results are information about different processes in the form of files.  </p>
<p>The <code>/proc</code> directory is from where the Kernel sees the system. The Kernel does not see everything the user is doing in a system at all times. The Kernel saves all the processes running in the system inside the /proc directory as files or subdirectories. </p>
<p>Whenever the Kernel wants to see what is happening in the system, what process does it need to give CPU Time Slice to, allocate/take resources or switch processes in the core or something else, is known by the Kernel with this /proc directory only. </p>
<h1 id="heading-jobs">Jobs</h1>
<p>There can be a situation when you run a process in the terminal, and it takes a lot of time to execute, and until it finishes, you cannot run any other command in the same terminal. This is where the concept of ‘Jobs’ comes in. By writing <code>&amp;</code> at the end of any command like <code>python3 test.py &amp;</code>, it will run asynchronously and provide you with a Process ID. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667989519031/8MEskjFlk.png" alt="Screenshot from 2022-11-08 18-41-43.png" /></p>
<p>As you can see, the terminal has provided the PID (21266) of this file and the Job ID ( [1] ) as the output running in the background. We can view all the jobs running in the background with the command <code>jobs</code>. It shows the exact command (process), the status as ‘Running’ and the Job ID as 1. </p>
<p>Now, if we write another command like <code>cat &amp;</code>, it will show the Job ID as 2 with the + sign in front of it. The python command's Job ID sign has changed from + to – because it is older in chronological order. If you write another <code>cat &amp;</code>, its Job ID will be 3 and the sign will be + while the previous command sign has changed to – and the python one has gone blank.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667989607317/8Mb-vnGFQ.png" alt="Screenshot from 2022-11-08 18-52-09.png" /></p>
<p>To bring a job from the background to the foreground, you can run the command <code>fg %1</code> where 1 is the Job ID of the Process. </p>
<p>Let us say I run the command <code>python3 test.py</code> and sometime later decide it is taking a lot of time, so I should send it to the background. I can click Ctrl+Z to stop it first. Remember, Ctrl+C terminates a process, but Ctrl+Z stops it. If we now write the command <code>bg</code>, it will send it to the background and make it run once again. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667989701660/ntDxKndJw.png" alt="Screenshot from 2022-11-08 19-00-53.png" /></p>
<p>If I want to kill this command midway, one way is to run <code>fg %5</code> where 5 is the Job ID, bring it to the foreground and press Ctrl+C. The other way to kill the process without bringing it to the foreground is by running the command <code>kill %5</code> where 5 is the Job ID. </p>
<p>Thanks for reading :)</p>
<p>To read the previous blogs of this Linux Series, go to <a target="_blank" href="https://blog.gauranggaur.com/">blog.gauranggaur.com</a></p>
<p>To see the video lecture of this blog, go to this <a target="_blank" href="https://www.youtube.com/watch?v=cnbvsWKf-qM&amp;list=PL2kSRH_DmWVZp_cu6MMPWkgYh7GZVFS6i&amp;index=6">youtube video</a></p>
<p>Follow me on <a target="_blank" href="https://twitter.com/gaurangcodes">Twitter</a></p>
<p>Do comment your thoughts, questions or anything unique you learned below!</p>
]]></content:encoded></item><item><title><![CDATA[User Management and Permissions in Linux: Everything you need to know]]></title><description><![CDATA[Users and Groups. Root and Other Users. Creating Editing Deleting Users. Changing Passwords. Change Permissions. suid, sgid and sticky bit. Processes]]></description><link>https://kshitijcodes.hashnode.dev/user-management-and-permissions-in-linux-everything-you-need-to-know</link><guid isPermaLink="true">https://kshitijcodes.hashnode.dev/user-management-and-permissions-in-linux-everything-you-need-to-know</guid><category><![CDATA[Ubuntu]]></category><category><![CDATA[Linux]]></category><category><![CDATA[linux for beginners]]></category><category><![CDATA[operating system]]></category><category><![CDATA[Devops]]></category><dc:creator><![CDATA[Kshitij Sharma]]></dc:creator><pubDate>Fri, 04 Nov 2022 09:47:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1667554761568/xfLhVKDEW.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-user-management">User Management</h1>
<h2 id="heading-users-and-groups">Users and Groups</h2>
<p>When you run a process in Linux, you always run it as the owner of that process. Whatever files we have in our system, their access and ownership are permission-dependent. </p>
<p>Let's say, we have two users in the same Linux system: Adam and David. Adam can never access any of the files that belong to David and vice-versa. Every user has their own Home Directory where their user-specific files are stored.  </p>
<p>If you open the terminal and enter the command <code>pwd</code>, it will give you a result like <code>/home/lenovo</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667551274570/PsT18KEbR.png" alt="Screenshot from 2022-10-31 18-46-49.png" /></p>
<p>Here, <code>lenovo</code> is the username. If I had another user in this system named <code>david</code>, there would be a separate directory called <code>/home/david</code>. Only humans use usernames as a simpler way to identify the user. </p>
<p>But the Linux system uses a different way to identify a user. It stores a unique ID for every user called UID. The system also uses ‘groups’ to manage permissions. A group is a set of users with a similar set of permissions. </p>
<p>Imagine a scenario where you have a Linux system. Three types of employees use it in a company: 3 Web Developers, 2 DevOps Engineers, and 1 DBMS administrator. In such a situation, the admin can create groups for all categories of employees. Each group is assigned a unique GID, which helps the system identify the group. </p>
<h2 id="heading-other-users">Other Users</h2>
<p>Even if you are the only human working with a Linux system, you are not the only user. There are other users as well, not necessarily a human. These users could be system daemons, which means processes that confirm everything runs smoothly and seamlessly in a system.  </p>
<h3 id="heading-root-user">Root user</h3>
<p>The most powerful user in the Linux system is the ‘root/superuser’. It can access any file and start/terminate any process in the entire system. </p>
<p>If you enter the command <code>cat /etc/shadow</code> in the terminal, it will show <code>Permission denied</code>. Because you, as a regular user, do not have sufficient permissions to view this file. If you enter <code>ls -l /etc/shadow</code> and check the detailed version of this file, you’ll find that this file belongs to the root user. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667551382031/Q-41B6Eap.png" alt="Screenshot from 2022-11-01 18-01-46.png" /></p>
<h3 id="heading-sudo-command">Sudo command</h3>
<p>If you want to get the root access and read the <code>/etc/shadow</code> file, you need the help of a command known as <code>sudo</code>. It stands for ‘superuser do’. You can enter <code>sudo cat /etc/shadow</code>, and the system will ask for your password. And once you press enter after typing it, the terminal will display the file data. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667551470903/HDX1hNKVX.png" alt="Screenshot from 2022-11-01 18-04-52.png" /></p>
<p>If you want to use the terminal as a root user without typing <code>sudo</code>, you can use the command <code>sudo su</code>. As you can see below, all the commands you enter now will be as the root user. You do not need to write <code>sudo</code> or enter the password. Whatever commands you enter as the root user after <code>sudo su</code>, are not registered in the history.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667551579779/6aH3_Atcs.png" alt="Screenshot from 2022-11-01 18-13-23.png" /></p>
<blockquote>
<p><strong>Warning:</strong> Making yourself the root user and using the system is not recommended because you may make critical mistakes like deleting or destroying something important and crashing your system.</p>
</blockquote>
<p>To exit the root environment, you can enter the command ‘exit’ and return to being a regular user. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667551700112/fWGVE55FA.png" alt="Screenshot from 2022-11-01 18-14-53.png" /></p>
<blockquote>
<p><strong>Tip:</strong> You can check the list of all users that have permission to use the <code>sudo</code> command. Linux system stores the list in a file you can read using the command ‘sudo cat /etc/sudoers’. If you want a user to have or not have access to the <code>sudo</code> command, you can add or remove that user from this list.</p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667551754876/2e9cXVhMa.png" alt="Screenshot from 2022-11-01 18-29-08.png" /></p>
<h3 id="heading-users-other-than-you-and-sudo">Users other than you and sudo</h3>
<p>As we understood earlier, there are many users in a Linux system. Two of them are you and root. Let’s talk about some others. If you enter the command <code>sudo cat /etc/passwd</code>, the terminal will show the list of all these users. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667551819397/NZEbFyj02.png" alt="Screenshot from 2022-11-01 18-35-10.png" /></p>
<p>As you can see above, the users are like lenovo, daemon, mongodb, mysql etc. Each user in the list is responsible for running their specific processes. It might be different in your results for the same command. </p>
<h3 id="heading-etcpasswd">/etc/passwd</h3>
<p>Each line in the result of <code>sudo cat /etc/passwd</code> looks like this: </p>
<p><code>root:x:0:0:root:/root:/bin/bash</code></p>
<p>Each element of this line is separated by a colon. Let’s break this line down and understand all elements one by one. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667553377645/1fhtRZvcC.png" alt="2.png" /></p>
<ol>
<li>Username - It will be different for every user. For a user named ‘lenovo’, it will be ‘lenovo’. </li>
<li>Password - This is ‘x’ here because the system stores it in another file ‘/etc/shadow’. </li>
<li>User ID (UID) - Every user in the system is assigned a unique user ID. </li>
<li>Group ID (GID) - Every group has a unique ID assigned to them by the system. </li>
<li>User info – Here it is ‘root’ based on the username. It can also be any contact detail or any other user info.</li>
<li>User’s Home Directory </li>
<li>Shell – Here it is root itself, but for a regular user like ‘lenovo’, it will be ‘/home/lenovo’Let’s talk about the ‘/etc/shadow’ file now.</li>
</ol>
<h3 id="heading-etcshadow">/etc/shadow</h3>
<p>If you enter the command <code>sudo cat /etc/shadow</code>, the terminal will display all users' password data.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667551897101/6QNRRsQxP.png" alt="Screenshot from 2022-11-03 13-22-11.png" /></p>
<p>Let’s take the first line containing the root user password details and understand each part. As you noticed, the last three values divided by a colon are empty. I'll explain them as well. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667553432897/861-i-VHN.png" alt="3.png" /></p>
<ol>
<li>Username </li>
<li>Encrypted Password of the user – For the root user, this is ‘!’ but for a normal human user, it will be an encryption key. </li>
<li>Date of last password change – This is the number of days since 1st January 1970. </li>
<li>Minimum Password age – This is the number of days you have to wait to change the password. If it was 30, you would have to wait for 30 days to change the password again. </li>
<li>Maximum Password Age – This is the opposite of the above one. The number of days you can keep your password, after which you have to change it.</li>
<li>Warning Period – The number of days after the Max password age after which the system will start warning you to change your password. </li>
<li>Password Expiry Period – The number of days passed after password expiry. It is empty because 99999 days since 1970 have not passed yet. </li>
<li>Account Expiration Date – This is empty here as this is the root user. But for a regular user created in the system, its account expiration date can be customized at the time of creation. </li>
<li>Reserved Field – The dev community of Linux hasn’t yet figured out what to use this field for. If they figure it out in the future, they might fill or assign it with some value. But for now, it’s just an empty reserved field.</li>
</ol>
<p>In most distros today, the authentication does not depend only on <code>/etc/shadow</code>. In the modern ecosystem, there is another system known as PAM (Pluggable Authentication Module).  </p>
<h3 id="heading-etcgroup">/etc/group</h3>
<p>Just like the above two files are for user and their password data. This one belongs to all the groups in the Linux system. If you enter the command <code>sudo cat /etc/group</code>, the terminal will show the group data the same way the above two files did. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667552015899/7FVYQwOHp.png" alt="Screenshot from 2022-11-03 14-08-28.png" /></p>
<p>Each group’s data is stored as lines with several line elements separated by a colon. Let’s break down the first line and understand. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667553980592/3Y5Fa98S_.png" alt="4 (1).png" /></p>
<ol>
<li>Group name </li>
<li>Group password – There is generally no use for a group password. But if there is, you can create one to store it here. </li>
<li>GID (Group ID) </li>
<li>List of users – Here, it is empty, but in some groups, there can be one or more than one user, and their names are divided by commas. </li>
</ol>
<h2 id="heading-creating-editing-and-deleting-a-user">Creating, Editing and Deleting a User</h2>
<h3 id="heading-create-and-delete-user">Create and Delete User</h3>
<p>If you enter the command <code>sudo useradd david</code>, this will create a new user named ‘david’ in your Linux system along with a new <code>/home/david</code> directory and new entries in <code>/etc/shadow</code>, <code>/etc/passwd</code>, and <code>/etc/group</code> files. When you will restart your system, it will show you two users and ask which one you want to log in to. </p>
<p>To delete this user, you can enter the command <code>sudo userdel david</code>, and it will delete/undo everything you created, like a new directory and other user file data. </p>
<h3 id="heading-changing-password">Changing Password</h3>
<p>If you want to change a user named ‘david’ password, you can do it by entering <code>sudo passwd david</code>. This command will help you change the password, and even edit the other details in <code>/etc/passwd</code> we discussed like minimum and maximum password age etc. </p>
<h3 id="heading-changing-hostname">Changing Hostname</h3>
<p>In the user details shown in the terminal like <code>lenovo@lenovo-Lenovo-ideapad-500-15ISK</code>, <code>lenovo-Lenovo-ideapad-500-15ISK</code> is the hostname. You can change that with the command <code>sudo hostname [new hostname]</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667552141658/6ihqmZVmn.png" alt="Screenshot from 2022-11-03 14-36-33.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667552147433/4C6qRwliw.png" alt="Screenshot from 2022-11-03 14-36-47.png" /></p>
<p>Once you reopen the terminal after executing the command with the desired hostname, it will display the new one as it did above. In my case, I changed it to my Twitter handle <a target="_blank" href="https://twitter.com/gaurangcodes">'gaurangcodes'</a>.</p>
<h1 id="heading-permissions">Permissions</h1>
<p>The whole above part of the blog was all about user management. Now let’s understand permissions. If you enter <code>ls -l</code>, the terminal will show a detailed version of all the files with various data elements. Let’s discuss each one, especially the first one which is most important. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667552358917/gX8-1SDDk.png" alt="Screenshot from 2022-11-03 15-43-28.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667553773441/AGF5TgR25.png" alt="5.png" /></p>
<ol>
<li>Permissions </li>
<li>Username – The name of the user that owns the directory. </li>
<li>Group name – The group that owns the directory. </li>
<li>Last time the directory was modified. </li>
<li>Name of the directory</li>
</ol>
<p>Let’s break down the first one, Permissions. Permissions always contain ten characters or bits. Divided into four types, are</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667553883870/fVMSXM_wG.png" alt="6.png" /></p>
<ol>
<li>Type – It tells you what type of file this is (everything in Linux is a file, even directories/folders). <code>d</code> represents ‘directory’. <code>-</code> represents a ‘file’ type with .extension. <code>l</code> represents ‘Link’. </li>
<li>User Permissions </li>
<li>Group Permissions </li>
<li>Other Permissions – If any other user gets access to these files, they will have this set of permissions.</li>
</ol>
<p>These permissions are of 4 types: r, w, x, - </p>
<ul>
<li>r: readability </li>
<li>w: writability </li>
<li>x: executability </li>
<li>'-' : Empty. No permission is granted</li>
</ul>
<p>The format in which permissions are written is always <code>rwx</code>: readable writable executable. r, w, and x are the symbolic representations of permissions. If any one of them is replaced by <code>-</code> means the user does not have that particular permission. For example, <code>r-x</code> means a user can read or execute the file but cannot write it. </p>
<p>Just like <code>rwx</code>, ‘u, g &amp; o’ are symbolic representations of the user, group and others. This will come in handy for changing the permission for any of them. </p>
<h2 id="heading-changing-permissions">Changing Permissions</h2>
<p>The <code>chmod</code> command stands for change or modify. You can change the permissions for any file or directory by executing it. For example, if I create a file testing.txt in a directory, it will not have 'write' permission for other users in the system, but I can change that by executing the command <code>chmod o+w testing.txt</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667552434558/4r5YZUne8.png" alt="Screenshot from 2022-11-03 16-24-36.png" /></p>
<p>As you can see, <code>-rw-rw-r--</code> changed to <code>-rw-rw-rw-</code>. </p>
<p><code>+</code> symbol is used to add permission like, <code>o+w</code> </p>
<p><code>-</code> symbol is used to remove permission like, <code>o-w</code> </p>
<p>You can also add/remove multiple permissions for multiple user types like <code>chmod ugo-rwx testing.txt</code>. But remember to maintain the order of <code>ugo</code> and <code>rwx</code>. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667552488633/20dYKSYKI.png" alt="Screenshot from 2022-11-03 16-30-32.png" /></p>
<h2 id="heading-numerical-representation-of-permissions">Numerical Representation of Permissions</h2>
<p>Using <code>ugo</code> and <code>rwx</code> representations is not the only way to change permissions. As they are also represented by numbers where: </p>
<p>R is equivalent to 4 </p>
<p>W is equivalent to 2 </p>
<p>X is equivalent to 1 </p>
<p>And </p>
<p><code>ugo</code> (user, groups, others) can have 4+2+1 = 7 (<code>rwx</code>) permissions or 0+0+0 = 0 (<code>---</code>) permissions. Let’s say you want to give all permissions to all three u,g &amp; o. For this, you can execute the command <code>chmod 777 testing.txt</code> where the order of numbers is maintained like, first for 'u', then for 'g', and last for 'o'. The permission subtotal can vary between 0 to 7 representing different combinations of permissions.</p>
<ul>
<li>0 – No permission </li>
<li>1 – Execute </li>
<li>2 – Write </li>
<li>3 – Write + Execute </li>
<li>4 – Read </li>
<li>5 – Read + Execute </li>
<li>6 – Read + Write </li>
<li>7 – Read + Write + Execute</li>
</ul>
<p>So between 0 to 7, all possible combinations of permissions covered that a user might need. But you need to maintain the order of u, g &amp; o. In 777, the first digit is for the user, the second is for the group, and the third is for others. </p>
<h2 id="heading-chown-and-chgrp-commands">chown and chgrp commands</h2>
<p>Earlier, we saw how every file has an owner user. We can change that ownership for any file or directory by using the command <code>sudo chown [username] [file/directory name]</code>. <code>chown</code> command helps us change the ownership to any user we want.  </p>
<p>There is also a group that owns that file or directory. You can change that by using <code>sudo chgrp [group name] [file/directory name]</code>. </p>
<p>You can change both user and group ownership at the same time by using the command <code>chown</code> itself by using a colon to combine username and group name like, <code>sudo chown newuser:someothergroup testing.txt</code>. </p>
<h2 id="heading-umask-command">umask command</h2>
<p>When you create a new file or directory, it is assigned a default set of permissions for the user, group and others. You can change what default permissions they get by using the command ‘umask’ like <code>umask 022</code>. But this does not work like <code>chmod</code>. Instead, it subtracts 777 from 022 like 7-0 = 7, 7-2 = 5, 7-2 = 5. So, the set of permissions will be 755 and not 022. </p>
<h2 id="heading-suid-sgid-and-sticky-bit-permissions">suid, sgid, and sticky bit permissions</h2>
<p>###suid 
suid stands for Set UID. As we all know, a regular user does not have access to the root files. And if you try to use <code>sudo</code>, the terminal will ask you for the password. If you are in an office environment, you might not know it and have to call the System Admin to enter it. If there is a root file you need to execute multiple times a day, it might not be possible to call the sysadmin to enter the password. In such situations, the ‘suid’ command comes in handy. </p>
<p>It will help you grant r, w, or x access to root files without using <code>sudo</code> in future. It means you can use them as the owner. ‘suid’ can be executed using either alphabetical (ugo and rwx) representation or numerical (777) representation.  </p>
<p>Let's understand this with an example. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667552554874/S1mHbr90p.png" alt="Screenshot from 2022-11-03 17-54-56.png" /></p>
<p>If we execute <code>ls -l /etc/shadow</code>, you can see that this file belongs to the root user. Now let’s try to execute this file with root privileges without using <code>sudo</code> and entering the password.  </p>
<p>Just like <code>rwx</code> represent read, write and execute permissions. <code>s</code> represents special root privilege. If we execute <code>sudo chmod u+s [filename]</code> or <code>sudo chmod 4755 [filename]</code>. Here, <code>s</code> and the first digit of <code>4</code> represent that special root privilege that you will be granted. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667552609711/jBiA9umQr.png" alt="Screenshot from 2022-11-03 18-09-57.png" /></p>
<p>As you can see, the permissions changed to <code>-rwsr-xr-x</code>. This <code>s</code> in the user section means you can execute the file now without <code>sudo</code>. </p>
<p>But what happens if you execute <code>sudo chmod 4655 testing.txt</code>? The <code>6</code> here means the execute permission digit (1) is not included for the user (4655 instead of 4755).  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667552853339/fGZ4mYhCf.png" alt="Screenshot from 2022-11-04 14-36-39.png" /></p>
<p>Now the small <code>s</code> is not there instead it’s capital <code>S</code>. This means you have the owner’s permission but still cannot execute the file because you entered 6 instead of 7, which omitted the execute permission. </p>
<h3 id="heading-sgid">sgid</h3>
<p>Just like ‘suid’, there’s ‘sgid’ as well, represented by the digit <code>2</code>. If you execute <code>sudo chmod g+s [filename]</code> or <code>sudo chmod 2755 [filename]</code>, it will do the same thing but for groups. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667552959963/zQPYjTqEW.png" alt="Screenshot from 2022-11-03 18-25-41.png" /></p>
<p>As you can see, the <code>s</code> has shifted and permissions have changed to <code>-rwxr-sr-x</code>. </p>
<h3 id="heading-sticky-bit">Sticky bit</h3>
<p>The Sticky bit is the permission for deletion. It means any user may read, write, or execute a file, but only the owner can delete it and nobody else. Let’s understand it in detail. </p>
<p>If you execute <code>ls -ld /tmp</code> where we’re using <code>-ld</code> flag instead of <code>-l</code>, it will show the detailed info of the directory instead of the contents inside. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667553020222/-PtpAKw0_.png" alt="Screenshot from 2022-11-03 18-42-06.png" /></p>
<p>Did you notice something? The last <code>x</code> in permissions is not there, instead is replaced by <code>t</code>. This <code>t</code> is the sticky bit. </p>
<p>You can do this too by using the command <code>sudo chmod +t [directory]</code> or <code>sudo chmod 1755 [directory]</code> where <code>1</code> stands for, as you might have guessed, the sticky bit. </p>
<p>Earlier, we learned that 4 represents readability, 2 represents writability, and 1 represents executability. But when 4, 2, or 1 are prepended to the <code>rwx</code> numerical representation as we saw in the above examples, </p>
<p>4 becomes suid </p>
<p>2 becomes sgid</p>
<p>1 becomes sticky bit </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667553096260/k6FqPoDpk.png" alt="Screenshot from 2022-11-03 18-52-15.png" /></p>
<p>As you can see, the last <code>x</code> has changed to <code>t</code>. This means only the owner user and the root (superuser) can delete this file. </p>
<h2 id="heading-process-permissions">Process Permissions</h2>
<p>Suppose you have two human users in the system, 'larry' with a UID of 600 and ‘david’ with a UID of 500. The one other user is the ‘root’ with a UID of 0.  </p>
<p>If user ‘larry’ tries to run the command <code>sudo passwd david</code> to change the password of user ‘david’, will he be able to change it? The answer is no, even though ‘larry’ is using the ‘sudo’ command. Let’s understand why. </p>
<p>When we execute a command, it is known as a process. There are three types of UIDs associated with any process. </p>
<ul>
<li>Effective UID – This belongs to the owner. If ‘larry’ is running the <code>sudo passwd david</code> command, he is running it as a root, so the effective UID will be 0. </li>
<li>Real UID – This belongs to the person who has launched the process. Here it’s ‘larry’, so the Real UID will be 600. </li>
<li>Saved UID – This UID switches between Effective and Real UID. Whenever you run a process, you never run it on higher privileges all the time, as you might end up messing up the system.</li>
</ul>
<p>When you start your system, in most cases, the Effective UID and Real UID are the same because the <code>s</code> permission we understood earlier is not that common in the system. Most of the time, the Effective UID is the person that owns the file/directory. </p>
<p>Coming to the question, why can't ‘larry’ change the password of ‘david’? Because although the Effective UID is 0 (of the root) with which the process is working, the Real UID is 600 (of the person who launched the process), which is different from the UID of 500 that you’re trying to change the password of, so the system will not allow it. </p>
<p>But if you do it as the root user, the system will allow it because the root/superuser is very powerful and can bypass anything in the system. </p>
<p>Thank you for reading :)</p>
<p>To read the other blogs of this Linux Series, you can go to <a target="_blank" href="https://blog.gauranggaur.com/">blog.gauranggaur.com</a></p>
<p>To see a video lecture of this blog, go to this <a target="_blank" href="https://www.youtube.com/watch?v=hxNFeL2qY-k&amp;list=PL2kSRH_DmWVZp_cu6MMPWkgYh7GZVFS6i&amp;index=17">youtube video</a></p>
<p>Follow me on Twitter <a target="_blank" href="https://twitter.com/gaurangcodes">here</a></p>
<p>Do comment your thoughts or anything unique you learned below!</p>
]]></content:encoded></item><item><title><![CDATA[Standard Streams and File Manipulation in Linux: Explained in Detail]]></title><description><![CDATA[Standard Streams, How to Use Pipe to Redirect Output, Environment Variables, Linux File Manipulation with Shell Commands: head tail sort tr uniq wc grep]]></description><link>https://kshitijcodes.hashnode.dev/standard-streams-and-file-manipulation-in-linux-explained-in-detail</link><guid isPermaLink="true">https://kshitijcodes.hashnode.dev/standard-streams-and-file-manipulation-in-linux-explained-in-detail</guid><category><![CDATA[linux-commands]]></category><category><![CDATA[Linux]]></category><category><![CDATA[linux for beginners]]></category><category><![CDATA[linux-basics]]></category><category><![CDATA[linux kernel]]></category><dc:creator><![CDATA[Kshitij Sharma]]></dc:creator><pubDate>Mon, 31 Oct 2022 11:00:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1667215486080/vqn5lQazp.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-three-standard-streams">Three Standard Streams</h1>
<p>Stream here means the transfer of data. That data is simple text. </p>
<h2 id="heading-stdin-standard-input">Stdin (Standard Input)</h2>
<p>Stdin has the code 0. Linux takes the standard input and gives an output. It can be a standard output or a standard error.</p>
<h2 id="heading-stdout-standard-output">Stdout (Standard Output)</h2>
<p>Stdout has the code 1. Standard output can be streamed at three places in your system: </p>
<ol>
<li>Terminal Window </li>
<li>some file </li>
<li>Given to a pipe, which redirects it however you want. </li>
</ol>
<p>If you want to store the text output in a file you can use the symbol <code>&gt;</code>. 
For example: If you want to store the <code>ls</code> command output in an output.txt file. You can write the command <code>ls &gt; output.txt</code>. If output.txt doesn’t exist, Linux will create it for you automatically. 
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667206129223/CrZkgZsX8.png" alt="Screenshot from 2022-10-29 19-10-27.png" /></p>
<p>Now, if you go to a different folder and want to store a command’s Stdout, you need to specify the path to output.txt like, <code>ls &gt; ~/output.txt</code> </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667206303353/s-Y94Alwp.png" alt="Screenshot from 2022-10-29 19-20-07.png" /></p>
<p>Notice that the previous entry of the <code>ls</code> output is overwritten with the new one. But you can avoid this and keep adding new entries without overwriting previous ones by using the symbol <code>&gt;&gt;</code> like <code>ls &gt;&gt; output.txt</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667206564545/xkAYh_RDw.png" alt="Screenshot from 2022-10-29 19-22-22.png" /></p>
<p>Notice that the previous Documents folder entry is still there while new entries are added. 
Controlled Stdout with <code>less</code> command </p>
<p>If you ever try to read a large file in the terminal, for example, with the command ‘cat /var/log/syslog’, it will populate your terminal with an extremely large output. It will become a hindrance for you to scroll up and down. To tackle this, you can do ‘less /var/log/syslog’, this will still display the file data in the terminal, but you can exit it by typing ‘q’ and your output will disappear as it is not populated in the terminal. </p>
<h2 id="heading-stderr-standard-error">Stderr (Standard Error)</h2>
<p>Stderr has the code 2. Let’s understand how Stderr is different from Stdout with an example. If you write the command <code>lg &gt; output.txt</code>, Linux will give a standard error, but will it be saved in output.txt? Let’s see what happens. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667206740696/y_sfwH5T7.png" alt="Screenshot from 2022-10-29 19-33-47.png" /></p>
<p>As you can see, the output.txt file did get overwritten but is empty. Because a Stderr is not output. It is a Standard error. Output.txt expected a Stdout, hence it is empty. </p>
<p>But let’s say you still want to store Stderr to output.txt. For that, you can use <code>2&gt;</code> instead of <code>&gt;</code> like <code>ls 2&gt; output.txt</code>. We are writing 2 here because it denotes the Stderr code that Linux recognizes. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667206956128/stxMOz-qt.png" alt="Screenshot from 2022-10-29 20-42-36.png" /></p>
<h1 id="heading-how-to-use-the-pipe-to-redirect-standard-output-as-standard-input">How to use the pipe to redirect Standard Output as Standard Input</h1>
<p>Let’s say, you want to use the <code>less</code> command with <code>ls -la /etc</code> but if done so, it will give an error as both the output-giving commands are clashing with each other and <code>less</code> is confusing <code>ls</code> with a file/directory name. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667207148756/h0GlfT3lk.png" alt="Screenshot from 2022-10-30 16-10-34.png" /></p>
<p>You can use pipe ( <code>|</code> ) here to use both <code>ls</code> and <code>less</code> commands together like <code>ls -la /etc | less</code> and it will work just fine. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667207407541/G0mK1q1G1.png" alt="Screenshot from 2022-10-30 16-20-08.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667207455094/uifv3g1qv.png" alt="Screenshot from 2022-10-30 16-20-12.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667207536239/S-60rK8jZ.png" alt="Screenshot from 2022-10-30 16-20-38.png" /></p>
<h2 id="heading-lets-understand-how-did-the-above-command-work-behind-the-scenes">Let’s understand how did the above command work behind the scenes.</h2>
<p>The <code>ls -la /etc</code> part of the command which is a Stdin gave a Stdout in response. But rather than populating on the terminal, it was transferred as a Stdin to the <code>less</code> part of the command by <code>|</code> (pipe) </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667209694921/LYq-GX9W8.png" alt="ls -la etc  less.png" /></p>
<p><strong>Summary:</strong> Pipe allows you to take Stdout of one command and pass it as Stdin to another command. </p>
<h1 id="heading-environment-variables">Environment Variables</h1>
<p>If you write <code>echo $HOME</code>, you’ll get something like <code>/home/lenovo</code>. If you do <code>echo $USER</code>, you’ll get <code>lenovo</code>. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667209964685/XA6Ph5u-X.png" alt="Screenshot from 2022-10-30 16-34-00.png" /></p>
<p>Here HOME and USER are environment variables. In simple words, environment variables are useful information that the shell and its child processes use. 
You can check out all the environment variables stored in your system by using the command <code>env</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667210222894/KSI3wwMIe.png" alt="Screenshot from 2022-10-30 16-47-46.png" /></p>
<p>Environment variables are not constant. They keep changing based on what you’re doing in the system. For example, if you write the command <code>echo $PWD</code> where PWD is an environment variable, you’ll get an output like <code>/home/lenovo</code>. But if you change your present working directory with the <code>cd</code> command, the PWD data will change with it as well. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667210323178/q3Fdelln9.png" alt="Screenshot from 2022-10-30 16-51-36.png" /></p>
<p>Now if you were wondering how the system gives out your location with the <code>pwd</code> command, it simply maintains an environment variable with that information and gives it out or uses it whenever the user desires. </p>
<h1 id="heading-everything-is-a-file-in-linux-even-the-commands">Everything is a file in Linux, even the commands</h1>
<p>If you type <code>echo $PATH</code>, you’ll find all the paths in which Linux checks for the command file that you have entered. If it doesn’t exist, you get the Standard error <code>Command not found</code>. The shell is saying that the file which executes that specific command is not found in any of the file paths stored in the PATH environment variable. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667210623234/oJlHvO5e6.png" alt="Screenshot from 2022-10-30 17-13-25.png" /></p>
<p>If you want to check the command files in one of these above paths, you can type any path like <code>ls /usr/bin</code> or for a better experience <code>ls /usr/bin | less</code> (to quit <code>less</code> environment, type ‘q’) </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667210760181/bcwpIdfjT.png" alt="Screenshot from 2022-10-30 17-18-46.png" /></p>
<p>As you can see, the commonly used commands like ‘apt’, ‘ls’, and ‘npm’ exist as files in 'usr/bin'</p>
<h1 id="heading-basic-shell-commands-to-interact-with-files">Basic shell commands to interact with files</h1>
<h3 id="heading-head-command">head command</h3>
<p>If you type <code>head [filename or filepath]</code>, it will show you the first ten lines that the file contains. If you want to see more or less lines, you can add the flag ‘-n’ and the number of lines like ‘head -n 5 /var/log/syslog’ </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667211072776/ZOEpDXVi-.png" alt="Screenshot from 2022-10-30 17-36-01.png" /></p>
<h3 id="heading-tail-command">tail command</h3>
<p>You can do the same thing as <code>head</code> command but for the last ten lines. If you want to control the number of lines you want to display, use the flag <code>-n</code> with the desired number. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667211161238/9K5qCBaZg.png" alt="Screenshot from 2022-10-30 17-47-29.png" /></p>
<p>If you want to let the Stdout keep updating and populate your terminal, you can use the flag <code>-f</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667211349914/WTK1AAs0t.png" alt="Screenshot from 2022-10-30 17-49-18.png" /></p>
<p>As you can see, when I opened another terminal window, the terminal Stdout got updated with the information about the same (Read the third last line of Standard output).</p>
<h3 id="heading-sort-command">sort command</h3>
<p>This helps you sort the file content like below. You can also reverse sort the content with the flag <code>-r</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667211469596/Ln23easbx.png" alt="Screenshot from 2022-10-30 18-00-35.png" /></p>
<h3 id="heading-tr-command">tr command</h3>
<p>It takes a Standard input (Stdin) and translates or you can say, deletes and replaces it with a new, translated Standard Output (Stdout). You can use it with a pipe like <code>cat output.txt | tr a-z A-Z</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667211849582/aL_snhbH-.png" alt="Screenshot from 2022-10-30 18-12-52.png" /></p>
<h3 id="heading-uniq-command">uniq command</h3>
<p>Let’s say you have multiple lines with duplicate values, <code>uniq</code> command helps you display only the unique values as standard output. If you use <code>-c</code> flag, it will also show the number of occurrences of each value. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667212029098/tAyExjMvl.png" alt="Screenshot from 2022-10-30 18-17-35.png" /></p>
<p>If you only want the non-repeated values, then you can use the flag <code>-u</code>. Only four values are not repeated in the example and hence, displayed. 
To see the opposite of this, which is only the duplicated values, you can use the flag <code>-d</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667212124202/_iC2K82np.png" alt="Screenshot from 2022-10-30 18-27-12.png" /></p>
<p><strong>A problem you might face with uniq command </strong></p>
<p>Let’s say the file contains values that are not adjacent to each other, then will the <code>uniq</code> command work? </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667212230870/Azwv5LY0m.png" alt="Screenshot from 2022-10-30 18-33-56.png" /></p>
<p>The answer is no. As you can see, the repeated values are v, d, and r. But <code>uniq</code> command is not working on ‘v’ and ‘d’ unlike ‘r’. This is because r’s repetition happens in an adjacent way. </p>
<p><strong>The solution</strong> </p>
<p>A handy solution is to use the <code>sort</code> command and transfer its Stdout as Stdin to <code>uniq</code> command via pipe like <code>sort output.txt | uniq</code> </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667212394579/QlQTjjz73.png" alt="Screenshot from 2022-10-30 18-40-07.png" /></p>
<p>Now you can see that ‘v’ and ‘d’ do not repeat in the Stdout. </p>
<h3 id="heading-wc-command">wc command</h3>
<p><code>wc</code> command shows multiple count types of a file. If you write the command <code>wc output.txt</code>, it will give you three digits, which denote the number of lines, words and file size. </p>
<p>If you write <code>wc -l [filename or path]</code>, you’ll get only the number of lines. </p>
<p>If you write <code>wc -w [filename or path]</code>, you’ll get only the number of words. </p>
<p>If you write <code>wc -c [filename or path]</code>, you’ll get only the size of the file in bytes. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667212524431/m1yPjOuLZ.png" alt="Screenshot from 2022-10-30 21-35-18.png" /></p>
<h3 id="heading-grep-command">grep command</h3>
<p>It allows you to search files with the help of characters and regular expressions. For example, if you write <code>env | grep PWD</code>, you’ll get the search results with files that have PWD in their name. <code>env</code> command produces a standard output and pipe symbol (<code>|</code>) transfers it to the <code>grep</code> command as standard input. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667212643157/gsfoZ2b4d.png" alt="Screenshot from 2022-10-30 22-03-04.png" /></p>
<p>Not only it shows you PWD, but also OLDPWD, which means the previous directory you were in. If you write <code>cd -</code> command, it will send you back to that directory (OLDPWD). </p>
<p>Thank you for reading :)</p>
<p>To read the previous blog of this Linux Series, click <a target="_blank" href="https://blog.gauranggaur.com/an-introduction-to-linux">here</a></p>
<p> To see a video lecture of this blog, go to this <a target="_blank" href="https://www.youtube.com/watch?v=xVaC_G6aeH0&amp;list=PL2kSRH_DmWVZp_cu6MMPWkgYh7GZVFS6i&amp;index=3">youtube video</a></p>
<p>Follow me on Twitter <a target="_blank" href="https://twitter.com/gaurangcodes">here</a></p>
<p>Do comment your thoughts or anything unique you learned below!</p>
]]></content:encoded></item><item><title><![CDATA[An Introduction to Linux]]></title><description><![CDATA[What is an Operating System, Why Linux is preferred over Windows, where did Linux come from? history of linux, terminal and shell, basic shell commands]]></description><link>https://kshitijcodes.hashnode.dev/an-introduction-to-linux</link><guid isPermaLink="true">https://kshitijcodes.hashnode.dev/an-introduction-to-linux</guid><category><![CDATA[Linux]]></category><category><![CDATA[linux for beginners]]></category><category><![CDATA[linux-commands]]></category><category><![CDATA[linux-basics]]></category><category><![CDATA[linux kernel]]></category><dc:creator><![CDATA[Kshitij Sharma]]></dc:creator><pubDate>Fri, 28 Oct 2022 14:40:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1666967552382/diaUA2JZU.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-what-happens-when-you-start-a-computer">What happens when you start a computer?</h1>
<p>The first thing your computer does after starting is to run the BIOS (Basic Input-Output System). In other words, it executes the software that is in BIOS. BIOS, also known as firmware, is installed by default in the ROM (Read-only Memory) chip in the CPU motherboard.
That software checks if the system is working correctly or not. It will check if the memory is loading, if the RAM and Hard Disk are there, the devices connected to the system, whether the keyboard is connected, and many other preconditions to launching the Operating System.<br />Once the checks are over, it loads the Bootloader that starts the Operating System. A Bootloader is a computer program responsible for starting up the operating system. </p>
<h1 id="heading-what-is-an-operating-system">What is an Operating System?</h1>
<p>An Operating System or OS is the software responsible for managing the computing device and acts as an interface between the hardware and the user. The computing device can be a desktop, smartphone, ATM etc.<br />For software to be considered an OS, it needs a few pre-requisites:  </p>
<ol>
<li>Kernel: A Kernel is the core of any operating system with complete control over anything on the system. It facilitates the interaction between the software and the hardware. </li>
<li>File System: method or data structure that the OS uses to store and retrieve data in the memory. </li>
<li>User Interface (Command line interface or Graphical User interface) </li>
<li>Ability to manipulate data based on user commands</li>
</ol>
<h1 id="heading-why-do-software-engineers-prefer-linux-or-macos-over-windows">Why do Software Engineers prefer Linux or macOS over Windows?</h1>
<p>Linux and macOS are very similar as they are both UNIX-based. UNIX is a multitasking, multiuser operating system designed for flexibility and adaptability. On the other hand, Windows derives most of its functionalities from other operating systems. </p>
<ol>
<li>Linux is open source based. It makes feature updates and bug fixes a lot more frequent. If a developer finds a bug, s/he can raise the pull request. If it gets merged, it will be there in the next release. On the other hand, if a bug comes up in Windows, being a commercial product, the developers working on it make a list of all the bugs, fix them in one go and then come up with an update after a long time. </li>
<li>It supports almost all programming languages and offers a vast range of tools and applications useful for software development. </li>
<li>Linux Terminal is superior to Windows Command Prompt. The command line tools are developed natively for Linux, so it has better support. </li>
<li>Easier to get development-related things done in Linux. Like, as the ability to do Bash Scripting and SSH into some remote server.</li>
</ol>
<h1 id="heading-where-did-linux-come-from-history-of-linux">Where did Linux come from? History of Linux</h1>
<p>In 1969, two people, Ken Thompson and Dennis Ritchie developed the first Operating System called UNIX. A decade later, another person named Richard Stallman developed the GNU Project. Around that time, some other OS were also developed, like BSD and MINIX. All of them were similar to UNIX but lacked a unified Kernel. 
Then came Linus Torvalds in 1991, who started working on his side project while attending university. That project was Linux Kernel. Today this Linux Kernel is the unified kernel used by all Linux distributions that are out there, like Debian, Ubuntu, mintOS, fedora, arch Linux etc. </p>
<h1 id="heading-terminal-and-shell">Terminal and Shell</h1>
<p>You can access the terminal in your Linux distribution by pressing Ctrl+Alt+T. A Terminal is the text input/output environment that launches the shell. Now, what is a Shell? It is the command line interpreter. It executes every single command line-by-line, just like python does. You can say it is a program that takes your command from the keyboard and takes it to the kernel for execution. Most of the shells use Bash as their programming/scripting language.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1666966180234/NMhgnd9W-.png" alt="Screenshot from 2022-10-20 17-54-37.png" />
As you can see in the screenshot, <code>lenovo</code> is the username of the computing device. You can choose whatever name you want on your computer. After @, <code>lenovo-Lenovo-ideapad-500-15ISK</code> is the hostname. The <code>~</code> symbol represents the home directory; it will change to the name of the directory you enter.  </p>
<h2 id="heading-some-basic-commands-to-interact-with-the-os">Some basic commands to interact with the OS</h2>
<h3 id="heading-echo-command">echo command</h3>
<p>Whatever you write after echo, will be shown as the output. For example, <code>echo Hello World</code> will give the output ‘Hello World’ </p>
<h3 id="heading-pwd-command">pwd command</h3>
<p>It shows your present working directory or you can say, your location in the directory tree.  The folders or directories are located in the system based on the tree structure. All directories have a parent directory. <code>pwd</code> command displays the path based on this tree's hierarchical structure. If you are in the Desktop folder, it will show <code>/home/lenovo/Desktop</code> as the output. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1666966442385/DQNO-L9Vl.png" alt="Screenshot from 2022-10-20 18-11-28.png" /></p>
<h3 id="heading-ls-command">ls command</h3>
<p>It shows all the directories and files that are present in the present working directory you’re currently in. The output of <code>ls</code> command depends on your location in the tree hierarchy. If you write <code>ls -a</code> as the command where <code>-a</code> is the flag and will show all the hidden files as well. If you add <code>-l</code> flag along with <code>ls</code> command, it will show many other details (like date of creation, permissions etc.) of every single item present in the directory. You can combine both flags by writing <code>-la</code> </p>
<h3 id="heading-cd-command">cd command</h3>
<p>It helps you change your location in the directory tree hierarchy.  </p>
<p>By writing <code>cd ..</code> you can go back to a directory in the hierarchy. By using cd [directory name], you can go to that directory but it has to be present in your current directory. If it is not, then it will show <code>not found</code> output. Otherwise, you can also write a complete path to your desired directory after cd to tackle this problem, a path like <code>pwd</code> command shows. With <code>cd -</code> command you can go back to the previous directory. But this is not the same as <code>cd ..</code> command. <code>cd ..</code> takes you to the parent directory of the directory you were in. On the other hand, <code>cd -</code> takes you to the previous directory you were in, which is not necessarily the parent directory of the current directory as it is possible you switched to the current directory by putting cd [long path].</p>
<p>When you change the path, the exact hierarchy path gets added after the <code>~</code> sign which represents home.  </p>
<h3 id="heading-mkdir-and-rmdir-commands">mkdir and rmdir commands</h3>
<p><code>mkdir</code> command creates a new directory wherever you are situated in the hierarchy tree. Or wherever else you want by using the destination path and the <code>-p</code> flag like <code>mkdir -p /new_folder/newDirectory</code>, even if the new_folder does not exist, it will automatically create one for you.  </p>
<p><code>rmdir</code> command lets you remove the directory in the same way. But only if it does not have more directories inside it </p>
<p>If you want to remove a directory that has files and other subdirectories inside it, you have to use the command <code>rm</code> along with flag <code>–r</code> like <code>rm -r new_folder</code> or else the shell will give the error <code>directory not empty</code>. <code>-r</code> flag helps remove a directory recursively. To know exactly what rm –r folder command removed as the output, write rm <code>–rv</code> folder, where v means verbose. </p>
<h3 id="heading-touch-command">touch command</h3>
<p>This command creates a new file. You need to write the full name of the file with the extension like newfile.txt after touch like <code>touch newfile.txt</code> and this will create that desired file in whichever directory you are present. </p>
<h3 id="heading-cat-command">cat command</h3>
<p>It shows the content of the file, whatever is written in it. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1666966563181/S_odoafta.png" alt="Screenshot from 2022-10-20 20-47-47.png" /></p>
<h3 id="heading-history-command">history command</h3>
<p>It lists all the commands you have entered in the shell since the beginning. If you want to use a command you used previously without typing everything once again, you can press the up key on your keyboard. </p>
<h3 id="heading-cp-and-mv-commands">cp and mv commands</h3>
<p><code>cp</code> command will help you copy a file to any other folder with the help of its path. For example, if you write <code>cp test.txt new_folder/subfolder1</code>, this will copy test.txt to subfolder1.  </p>
<p><code>mv</code> command lets you do the same thing but rather than copying, it moves the file to the destination. This is like how you cut/paste in GUI. </p>
<p>If you want to copy or move a file without being present at the file’s location by using the cd command, you can write the whole path of the file instead like <code>cp ~/Desktop/test.txt ~/Desktop/new_folder/subfolder1</code> (cp [file path] [destination path]. </p>
<h3 id="heading-find-command">find command</h3>
<p>It helps you find a file or directory in your system. Use it like ‘find [where to find] [argument] [file name]’, for example, <code>find ~ -name file.txt</code>. If you don’t know the extension of a file but know only the name then you can write <code>file.*</code> instead of <code>file.txt</code>. If you only remember the extension but not the name, you can write <code>*.txt</code> instead of <code>file.txt</code>. You can also use another flag <code>-type</code> if you want to specify the type of the element you’re searching for example <code>–type d</code> for directory (<code>find ~ -type d -name new_folder2</code>).  </p>
<p><strong>TIP:</strong> There are many flags for each command in Linux. You can’t possibly remember all of them. Whenever you need to find usable flags for a command, simply write in the shell ‘man [command name]’ where man means manual. Or you can also use google search like, 'mkdir command flags' and check out blogs or official documentation if you’re not comfortable with the ‘man’ command output. </p>
<p>To know what a command does or what is its purpose, you can write the command `whatis’ like <code>whatis mkdir</code></p>
<p> To see a video lecture of this blog, go to this <a target="_blank" href="https://www.youtube.com/watch?v=Juo_0lpBMPY&amp;list=PL2kSRH_DmWVZp_cu6MMPWkgYh7GZVFS6i&amp;index=2">youtube video</a></p>
<p>Follow me on Twitter <a target="_blank" href="https://twitter.com/gaurangcodes">here</a></p>
<p>Do comment your thoughts or anything specific you learned below!</p>
]]></content:encoded></item><item><title><![CDATA[Everything you need to know about Static Keyword in Java: Explained in Detail]]></title><description><![CDATA[Why and How are Static Variables and Static Methods used in Java programming? Deploying Static inside Non-Static Method and Non-Static inside Static Method]]></description><link>https://kshitijcodes.hashnode.dev/everything-you-need-to-know-about-static-keyword-in-java-explained-in-detail</link><guid isPermaLink="true">https://kshitijcodes.hashnode.dev/everything-you-need-to-know-about-static-keyword-in-java-explained-in-detail</guid><category><![CDATA[Java]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Programming Tips]]></category><category><![CDATA[programming languages]]></category><category><![CDATA[Object Oriented Programming]]></category><dc:creator><![CDATA[Kshitij Sharma]]></dc:creator><pubDate>Tue, 01 Mar 2022 14:16:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1646143862388/jue-wwKCL.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-static-variables">Static Variables</h1>
<p>Let us understand the nature and role of the static keyword by looking at an example of a class and its instances. Like, the Phone class of a particular company. </p>
<pre><code><span class="hljs-keyword">public</span> class Phone { 
    <span class="hljs-keyword">int</span> ram; 
    <span class="hljs-keyword">string</span> color; 
    <span class="hljs-keyword">int</span> <span class="hljs-keyword">memory</span>; 
    <span class="hljs-keyword">int</span> price; 
    <span class="hljs-keyword">string</span> model; 
    long unitSold; 

    <span class="hljs-keyword">public</span> Phone (<span class="hljs-keyword">int</span> ram, <span class="hljs-keyword">string</span> color, <span class="hljs-keyword">int</span> <span class="hljs-keyword">memory</span>, <span class="hljs-keyword">int</span> price, <span class="hljs-keyword">string</span> model) { 
        <span class="hljs-built_in">this</span>.ram <span class="hljs-operator">=</span> ram; 
        <span class="hljs-built_in">this</span>.color <span class="hljs-operator">=</span> color; 
        <span class="hljs-built_in">this</span>.memory <span class="hljs-operator">=</span> <span class="hljs-keyword">memory</span>; 
        <span class="hljs-built_in">this</span>.price <span class="hljs-operator">=</span> price; 
        <span class="hljs-built_in">this</span>.model <span class="hljs-operator">=</span> model; 
        <span class="hljs-built_in">this</span>.unitSold <span class="hljs-operator">+</span><span class="hljs-operator">=</span> <span class="hljs-number">1</span>; 
   } 
}
</code></pre><p>Please notice, the <code>long unitSold;</code> is a special property that will remain the same for all the phone units sold. The <strong>total</strong> number of phones sold by a company cannot be different for a particular phone model/version the same way as human population property remains the same for all humans. 
Every instance of this Phone class should increase the units sold by 1 digit with the help of code line <code>this.unitSold += 1;</code> inside the constructor. </p>
<p>Now, let us create some objects with this Phone class.</p>
<pre><code><span class="hljs-keyword">public</span> class Main { 

    <span class="hljs-keyword">public</span> static void main { 

        Phone galaxyS3 <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Phone (<span class="hljs-number">8</span>, white, <span class="hljs-number">45999</span>, S3); 

        Phone galaxyS3Pro <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Phone (<span class="hljs-number">16</span>, white, <span class="hljs-number">65999</span>, S3); 

        Phone galaxyS4 <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Phone (<span class="hljs-number">16</span>, grey, <span class="hljs-number">78999</span>, S4); 



        System.out.println(galaxyS3.unitSold); 

        System.out.println(galaxyS3Pro.unitSold); 

        System.out.println(galaxyS4.unitSold); 
    }
}
</code></pre><p>Ideally, the result for all three print commands should be 3 in the console log because the company sold 3 smartphones in total. But that’s not the case. </p>
<pre><code>        System.out.println(galaxyS3.unitSold);          <span class="hljs-comment">//  1 </span>

        System.out.println(galaxyS3Pro.unitSold);    <span class="hljs-comment">//  1 </span>

        System.out.println(galaxyS4.unitSold);          <span class="hljs-comment">//  1</span>
</code></pre><p>The properties that are not related to the objects and remain the same for all the class objects, we declare them as ‘static’. The static properties belong to the class rather than the instances of that class. Hence, we shouldn’t use the ‘this’ keyword for static variables in the constructor and replace it with the class name itself. So, we’ll use <code>Phone.unitSold</code> instead of <code>this.unitSold</code></p>
<pre><code><span class="hljs-keyword">public</span> class Phone { 

    <span class="hljs-keyword">int</span> ram; 

    <span class="hljs-keyword">string</span> color; 

    <span class="hljs-keyword">int</span> <span class="hljs-keyword">memory</span>; 

    <span class="hljs-keyword">int</span> price; 

    <span class="hljs-keyword">string</span> model; 

    static long unitSold; 



    <span class="hljs-keyword">public</span> Phone (<span class="hljs-keyword">int</span> ram, <span class="hljs-keyword">string</span> color, <span class="hljs-keyword">int</span> <span class="hljs-keyword">memory</span>, <span class="hljs-keyword">int</span> price, <span class="hljs-keyword">string</span> model) { 

        <span class="hljs-built_in">this</span>.ram <span class="hljs-operator">=</span> ram; 

        <span class="hljs-built_in">this</span>.color <span class="hljs-operator">=</span> color; 

        <span class="hljs-built_in">this</span>.memory <span class="hljs-operator">=</span> <span class="hljs-keyword">memory</span>; 

        <span class="hljs-built_in">this</span>.price <span class="hljs-operator">=</span> price; 

        <span class="hljs-built_in">this</span>.model <span class="hljs-operator">=</span> model; 

        Human.unitSold <span class="hljs-operator">+</span><span class="hljs-operator">=</span> <span class="hljs-number">1</span>; 

     } 

}
</code></pre><p>Now the result for units sold will be 3 in the console log. Every time we create a new object, the <code>unitSold</code> value increases by 1. </p>
<pre><code>        System.out.println(galaxyS3.unitSold);          <span class="hljs-comment">//  3 </span>

        System.out.println(galaxyS3Pro.unitSold);    <span class="hljs-comment">//  3 </span>

        System.out.println(galaxyS4.unitSold);          <span class="hljs-comment">//  3</span>
</code></pre><p>Static variables are not dependent on objects. Even without creating a single object, you can still access the static variable via <code>Class.staticVariable</code> or <code>Phone.unitSold</code></p>
<h2 id="heading-initialization-of-static-variable">Initialization of Static Variable</h2>
<p>Initialization is the process of assigning a value to a variable. For example, <code>int a;</code> is declared, and we can initialize it by doing <code>int a = 12;</code> </p>
<p>Now for normal variables in a class, there are constructors to initialize the variables when new objects are created/instantiated like <code>this.property = property;</code> </p>
<p>But in the case of static variables, there are no objects. Here, the Static block comes into the picture. Static block <strong>only runs once</strong> and helps us initialize static variables inside a class.</p>
<pre><code>Public class StaticBlock { 

    static <span class="hljs-keyword">int</span> a <span class="hljs-operator">=</span> <span class="hljs-number">4</span>; 

    static <span class="hljs-keyword">int</span> b;              <span class="hljs-comment">// only declared, not initialized </span>


    static {                     <span class="hljs-comment">// this is a static block </span>

        b <span class="hljs-operator">=</span> a<span class="hljs-operator">*</span><span class="hljs-number">5</span>;            <span class="hljs-comment">//this will only run once when the program is loaded </span>

    } 


    <span class="hljs-keyword">public</span> static void main (String[] args) { 

        StaticBlock obj <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> StaticBlock (); 

        System.out.println (StaticBlock.a <span class="hljs-operator">+</span> “ and ” <span class="hljs-operator">+</span> StaticBlock.b);     <span class="hljs-comment">// 4 and 20 </span>

    } 

}
</code></pre><h1 id="heading-static-methods">Static Methods</h1>
<h2 id="heading-public-static-void-main">public static void main</h2>
<p>This is the most familiar static method to anyone who has known java for a while. The question is, why this main method of the Main class is static? </p>
<p>This main method is the <strong>very first thing</strong> that is run by any java program. All the classes and objects have their references in the <code>public static void main(){}</code> function and are run through it. Without this main function, you <strong>cannot run</strong> any java program. </p>
<p>Let’s say you decide to remove the ‘static’ keyword and run the function as <code>public void main(){}</code> Java won’t be able to run this program because any function inside a class needs an object to run itself.  </p>
<p>But it is impossible to create an object as any java program <strong>requires</strong> the main function to run <strong>first</strong>. Without it, you won’t even find the option to run the code. And if you can’t run the code, how will you create the object? And if you can’t create the object, how will you run the main function? This is the crazy paradox ‘static’ functionality helps us to break. </p>
<p>How? A static function doesn’t require an object to run itself. So, we can run the main function as the first function without an object by making it static. </p>
<h2 id="heading-non-static-method-inside-static">Non-static method inside static</h2>
<p>An example of non-static method inside a static one: </p>
<pre><code><span class="hljs-type">void</span> greeting () { 

    <span class="hljs-keyword">System</span>.<span class="hljs-keyword">out</span>.println (“Hello world”); 

}
</code></pre><p>The above method can't be deployed inside a static method like</p>
<pre><code>Public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main { 

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">greeting</span> (<span class="hljs-params"></span>)</span> { 

    System.<span class="hljs-keyword">out</span>.println (“Hello world”); 

    } 

} 

<span class="hljs-comment">//OR</span>

<span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">greets</span> (<span class="hljs-params"></span>)</span> { 

    greeting (); 

}
</code></pre><p><strong>This will show an error and won’t run.</strong> </p>
<p>Why? Because inside any static method, you cannot run a non-static method. Anything non-static belongs to or <strong>requires an object to come into existence</strong>. And a static method does not depend on an object. Hence, you can’t have something inside static that does depend on an object. </p>
<h3 id="heading-how-to-deploy-a-non-static-method-inside-a-static-method">How to deploy a non-static method inside a static method?</h3>
<p><strong>The problem we are facing:</strong> The non-static object <code>greeting();</code> does not belong to an object. </p>
<p><strong>The way to solve this problem:</strong> We can create a new object of the Main class and assign the <code>greeting();</code> method to it. </p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">greets</span> <span class="hljs-params">()</span> </span>{ 

    Main obj = <span class="hljs-keyword">new</span> Main (); 

    obj.greeting(); 

}
</code></pre><p>Now the static method will accept the non-static <code>greeting();</code> method as it belongs to an object now.</p>
<h2 id="heading-static-method-inside-non-static">Static method inside non-static</h2>
<p>An example of non-static method inside static: </p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">greets</span> <span class="hljs-params">()</span> </span>{       <span class="hljs-comment">// this is a static function that </span>

    greeting (); 

} 



<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">greeting</span><span class="hljs-params">()</span> </span>{         <span class="hljs-comment">// can be deployed inside non-static greeting() function </span>

    greets(); 

}
</code></pre><p>This is possible without any error because a static method does not depend on any object and is independent. Hence, it can be deployed anywhere in the program. </p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Any static variable or method belongs to the class and not to the instances of that class. Anything static is independent of objects and does not need to assign itself to an object. Hence, static variables or functions can be placed anywhere in a java program, including all non-static objects or functions. </p>
]]></content:encoded></item><item><title><![CDATA[When, Where and Why to use ‘this’ keyword in Java?]]></title><description><![CDATA['this' keyword helps create unlimited Objects with Class, Constructor, new keyword and dot operator. 'this' binds Object arguments to class properties]]></description><link>https://kshitijcodes.hashnode.dev/when-where-and-why-to-use-this-keyword-in-java</link><guid isPermaLink="true">https://kshitijcodes.hashnode.dev/when-where-and-why-to-use-this-keyword-in-java</guid><category><![CDATA[Java]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Object Oriented Programming]]></category><category><![CDATA[Objects]]></category><dc:creator><![CDATA[Kshitij Sharma]]></dc:creator><pubDate>Mon, 07 Feb 2022 07:55:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1644220025503/wbZeolq4LJ.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>To understand the role of ‘this’ in Java-based Object-Oriented Programming, you need to understand the series of events that happen before the ‘this’ keyword comes into the picture. If you already know that stuff, feel free to move forward directly to the desired section of this article.</p>
<h1 id="heading-what-are-classes-and-objects">What are Classes and Objects?</h1>
<p>Class is a template that Objects use to come into existence. An Object’s properties and functions are all derived from its Class.</p>
<p>Let’s understand with the help of an example: </p>
<p>If you want to store data of 5 employees. For salary numbers, you can do it in an array, like <code>int [] salary = new int [5];</code> Now you want to store employee names, you can do <code>String [] name = new String [5];</code> And for years of experience, you can do <code>float [] exp = new float [5];</code>
But how do we combine all three above data types into a single entity, a custom datatype? We can do it via Class. </p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span> </span>{ 
    <span class="hljs-keyword">String</span> name;  
    <span class="hljs-keyword">int</span> salary; 
    <span class="hljs-keyword">float</span> exp; 
}
</code></pre><p>How do we create multiple Objects of different employees by using this Class?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1644209276758/gqNAuHwbZ.png" alt="20220207_091119_0000.png" /></p>
<p>Before that, we need to understand how do we access the Class properties as all Employee Objects need these properties to come into existence and store data about themselves. We access/bind them with the Dot operator.</p>
<h1 id="heading-the-role-of-dot-operator">The Role of Dot Operator</h1>
<p>Dot Operator links the reference variable (employee1, employee2, employee3) with the instance variable (name, salary, exp).</p>
<p>For example, <code>employee1.name</code> will represent Michael.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1644214624507/OmaLXaCMf.png" alt="20220207_091119_0001.png" /></p>
<p>But there’s a problem. If you declare <code>Employee employee1;</code> and type <code>System.out.println(employee1.name);</code> The console should have shown ‘null’ as the default value. Instead, the compiler will give an error that variable employee1 has not been initialized and does not acquire any space in the heap memory.</p>
<p>Here the ‘new’ keyword comes in. </p>
<h1 id="heading-the-role-of-new-keyword">The Role of ‘new’ Keyword</h1>
<p>To create the Objects, you need the ‘new’ keyword. The ‘new’ keyword initializes, means allocates memory for the Object at runtime.</p>
<pre><code>Employee employee1 <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Employee ();
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1644217769991/NTL9xaSzGU.png" alt="20220207_123814_0000.png" /></p>
<p>Now if you type <code>System.out.println(employee1.name);</code> it will print ‘null’ in the console, which is the default value of any String variable. Now we can successfully allocate value with the dot operator.</p>
<pre><code>employee1.<span class="hljs-built_in">name</span> <span class="hljs-operator">=</span> “Michael”; 
employee1.salary <span class="hljs-operator">=</span> <span class="hljs-number">150000</span>; 
employee1.exp <span class="hljs-operator">=</span> <span class="hljs-number">2</span>.5f; 

employee2.<span class="hljs-built_in">name</span> <span class="hljs-operator">=</span> “Emily”; 
employee2.salary <span class="hljs-operator">=</span> <span class="hljs-number">180000</span>; 
employee2.exp <span class="hljs-operator">=</span> <span class="hljs-number">3</span>.5f;
</code></pre><p>But did you notice this process of binding is quite repetitive? We have to write employee1 again and again. We can use a shortcut and allocate data to their respective instance variables (like Michael to name and 150000 to salary).<br />Here the Constructor comes in.  </p>
<h1 id="heading-the-role-of-a-constructor">The Role of a Constructor</h1>
<p>A Constructor is a special built-in type of Function in the Class that runs and defines what happens when we create an Object. We can allocate the data by writing it in the argument of a constructor function. If we don’t write the data, the constructor will bind default values (like null, 0 and 0.0) to the Object.<br />For Constructor to bind the values written in the brackets like <code>new Employee (“Michael”, 150000, 2.5);</code> we need to write the Constructor function inside the Class like: </p>
<pre><code>class Employee { 
         String name;  
         <span class="hljs-keyword">int</span> salary; 
         float exp; 

         Employee () { 
                 employee1.<span class="hljs-built_in">name</span> <span class="hljs-operator">=</span> “Michael”; 
                 employee1.salary <span class="hljs-operator">=</span> <span class="hljs-number">150000</span>; 
                 employee1.exp <span class="hljs-operator">=</span> <span class="hljs-number">2</span>.5f; 
         } 
}
</code></pre><p>But this will give you an error. Class is a template to create multiple Objects. You can’t mention only one employee or custom object inside the Class. You won’t make a separate constructor for each employee as that would be counterproductive and repetitive.</p>
<p>We need a way to add values to properties of multiple Objects with the same Constructor. We need one word to access every Object and bind the Constructor argument with the Class properties. So that the Constructor can automatically replace that word like <code>word.name</code> with Object names like <code>employee1.name</code>, <code>employee2.name</code> or <code>employee3.name</code>.</p>
<p>Here the keyword ‘this’ comes into the picture.  </p>
<h1 id="heading-the-role-of-this-keyword">The Role of ‘this’ keyword</h1>
<p>The ‘this’ keyword helps us bind the arguments of a Constructor function like <code>new Employee (“Michael”, 150000, 2.5);</code> with the respective properties like name, salary, exp present inside the Class to be inherited by all Objects.<br />With the ‘this’ keyword, we can create as many employee Objects as we want without repeatedly writing code like <code>employee1.name = “Michael”</code>, <code>employee2.name = “Emily”</code>, <code>employee3.name = “Ryan”</code>.</p>
<pre><code>class Employee { 
             String name;  
             <span class="hljs-keyword">int</span> salary; 
             float exp; 

             Employee (String name, <span class="hljs-keyword">int</span> salary, float exp) { 
                             <span class="hljs-built_in">this</span>.<span class="hljs-built_in">name</span> <span class="hljs-operator">=</span> name; 
                             <span class="hljs-built_in">this</span>.salary <span class="hljs-operator">=</span> salary; 
                             <span class="hljs-built_in">this</span>.exp <span class="hljs-operator">=</span> exp; 
             } 
}
</code></pre><p>In the code above, <code>this.name = name;</code> doesn’t have to be that way. You can write a different argument name in the Constructor, for example: </p>
<pre><code>class Employee { 
          String name;  
          <span class="hljs-keyword">int</span> salary; 
          float exp; 

          Employee (String empName, <span class="hljs-keyword">int</span> salaryOfEmployee, float expYears) { 
                          <span class="hljs-built_in">this</span>.<span class="hljs-built_in">name</span> <span class="hljs-operator">=</span> empName; 
                          <span class="hljs-built_in">this</span>.salary <span class="hljs-operator">=</span> salaryOfEmployee; 
                          <span class="hljs-built_in">this</span>.exp <span class="hljs-operator">=</span> expYears; 
          } 
}
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1644214820329/ezGdv5Nsb.png" alt="20220207_091308_0000.png" /></p>
<p>We can also pass desired custom functions inside the Class like:</p>
<pre><code>class Employee { 
        String name;  
        <span class="hljs-keyword">int</span> salary; 
        float exp; 

        void greeting () { 
              System.out.println (“Hello everyone, my name <span class="hljs-keyword">is</span> ” <span class="hljs-operator">+</span> <span class="hljs-built_in">this</span>.<span class="hljs-built_in">name</span>);
        }

        Employee (String empName, <span class="hljs-keyword">int</span> salaryOfEmployee, float expYears) { 
                <span class="hljs-built_in">this</span>.<span class="hljs-built_in">name</span> <span class="hljs-operator">=</span> empName; 
                <span class="hljs-built_in">this</span>.salary <span class="hljs-operator">=</span> salaryOfEmployee; 
                <span class="hljs-built_in">this</span>.exp <span class="hljs-operator">=</span> expYears; 
        } 
}
</code></pre><p>If you write <code>employee1.greeting();</code> it will print “Hello everyone, my name is Michael”. If you write <code>employee2.greeting();</code> it will print “Hello everyone, my name is Emily”.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>From the series of events above, we understood that the 'this' keyword is the last step in the series that helps us create unlimited Objects with the help of a Class and its Constructor function. The 'this' keyword replaces itself with the Object name like employee1, employee2, employee3 and binds it to the Class Properties like name, salary, experience with the help of dot operator. We can use the 'this' keyword in self-made, custom functions inside the Class for attaching the different assigned values to Class properties for various Objects as we saw in the <code>greeting();</code> function.</p>
<p>Thanks for reading! :)</p>
]]></content:encoded></item><item><title><![CDATA[Types of Programming Languages: Everything you need to know]]></title><description><![CDATA[Types of programming languages and how are they used. Low Level-Assembly and Machine. High Level-Procedural, Functional, Object Oriented. Static and…]]></description><link>https://kshitijcodes.hashnode.dev/types-of-programming-languages-everything-you-need-to-know</link><guid isPermaLink="true">https://kshitijcodes.hashnode.dev/types-of-programming-languages-everything-you-need-to-know</guid><category><![CDATA[General Programming]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Functional Programming]]></category><category><![CDATA[programming languages]]></category><category><![CDATA[basics]]></category><dc:creator><![CDATA[Kshitij Sharma]]></dc:creator><pubDate>Fri, 04 Feb 2022 11:14:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1643971745461/yY8mRNwVD.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-what-is-a-programming-language">What is a Programming Language?</h1>
<p>A programming language is a language used by humans to interact with computers. Programmers assign tasks to machines by writing lines of code on what, why, when and how to do something. It can be anything. The possibilities are endless.</p>
<p>There are two main types of programming languages. Humans use High-level programming language to write tasks and machines use the low-level programming language to understand the assigned task.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643969193531/J0jfd2Z25.png" alt="1_20220204_144017_0000.png" /></p>
<h1 id="heading-low-level-programming-languages">Low-Level Programming Languages</h1>
<p>Low-Level Programming Languages are almost impossible to be understood by most programmers. They come into existence after the compilation of the programmer-written code to be understood by computer machines. Now there are two types of low-level programming languages: </p>
<h2 id="heading-assembly-language">Assembly Language</h2>
<p>Assembly language is a type of low-level language that is writable by humans but much closer to the understanding of computers. It is much faster to execute by the processor but is comparatively more difficult to write than high-level languages like c++, java etc. </p>
<p>Unlike English words like print and class, in Assembly language, we use mnemonics like LDA and STA that contain instructions like load and store. These mnemonic instructions get translated to machine language by the Assembler. 
Programmers wrote Assembly language frequently during the early days of programming. But now, it is done only when the performance and speed are of the highest importance for a software task or if the hardware is outdated. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643969691171/AUgz2rUeV.png" alt="2_20220204_144017_0001.png" /></p>
<h2 id="heading-machine-language-binary-code">Machine Language (Binary Code)</h2>
<p>Everyone is most familiar with this computer language. Thanks to the dropping green 0s and 1s in Matrix. Machine or Binary Language is hexadecimal sets of 16 0s and 1s that represent every single instruction and data fed to the computer by humans. Unlike Assembly and High-level languages, it does not need an Assembler or Compiler to be understood by the machine and is the closest to a computer’s understanding.</p>
<pre><code><span class="hljs-number">0101000000010000</span> : <span class="hljs-keyword">Add</span> sum <span class="hljs-keyword">to</span> the acc;
<span class="hljs-number">1011000000001010</span> : Jump <span class="hljs-keyword">to</span> done <span class="hljs-keyword">if</span> n &lt; <span class="hljs-number">0</span>;
</code></pre><h1 id="heading-high-level-programming-languages">High-Level Programming Languages</h1>
<p>It will be almost impossible to write instructions for the computer in 0s and 1s or mnemonics, so we created High-Level Programming Languages. They are human-friendly programming languages containing English words as commands. Programmers can turn their ideas into executable, instruction-based code and design everyday software and applications. They are executed by being translated to machine language by a compiler. There are two ways we can distinguish high-level programming languages. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643970219340/jNgSq7FUv.png" alt="3_20220204_144017_0002.png" /></p>
<h2 id="heading-procedural-programming-language">Procedural Programming Language</h2>
<p>This category comes from the initial days of programming. For a procedural programming language, the procedure is the priority and data come second. It uses a top-down approach where we break down a big problem into successively smaller chunks. It is easy to track the flow of a program and find bugs due to the well-structured, systematic order of statements.</p>
<p><strong>Examples of Procedural Programming Languages:</strong> Pascal, COBOL, C, Basic, Fortran, Python</p>
<h2 id="heading-functional-programming-language">Functional Programming Language</h2>
<p>Functions are a block of code with a set of instructions/calculation/solutions that we can repeatedly use by using the function’s name instead of writing all of the code once again. Functional Programming languages are the ones that treat functions as first-class citizens in their environment. It means the Functional language treats them like any other variable. We can pass functions as arguments in other functions, return them in a higher-order function, and assign them as a value to another variable. </p>
<p><strong>Examples of Functional Programming Languages:</strong> JavaScript, Python, Clojure, Elixir, Scala, Erlang, Haskell, Common lisp, Racket, SQL</p>
<h2 id="heading-object-oriented-programming-language">Object-Oriented Programming Language</h2>
<p>Object-oriented programming language revolves around objects. When we turn a dataset into code, it is known as an object. Let me explain with an example. An object ‘student’ consists of a name (string), roll number (integer), and percentage (float). Now, we can use the ‘student’ object as a custom datatype everywhere in the code.</p>
<p>Classes are templates, and Objects are their instances. In simple words, we create Objects using classes. Class is a template that Objects (like students) use for their structure. Classes can also contain functions that manipulate the data to produce desired results. </p>
<p>For example, if a Class (template) has a Function that decreases roll number by one digit, then all the Objects inherited (created) from that class will have this function and reduce their roll numbers by 1.</p>
<p>Object-oriented programming follows the bottom-up approach. Contrary to the top-down approach, we define small components and solve problems at a fundamental level. We link them to build elements and repeat the integration until we have a complete system/solution. This programming approach is the easiest and most efficient to solve real-world problems as every problem is treated as an entity.</p>
<p><strong>Examples of Object-oriented Programming Languages:</strong> Java, C++, C#, JavaScript, Python, PHP, Ruby, Swift, Kotlin, Scala, Common Lips</p>
<h2 id="heading-the-doubt-you-might-have">The doubt you might have</h2>
<p>In the examples, you may have noticed that some languages like Python and JavaScript are in multiple categories. So, the question is, do these programming languages support more than one approach to programming? The answer is yes! Most modern High-level programming languages are hybrid in structure and designed for general-purpose programming.</p>
<h1 id="heading-static-and-dynamic-programming-languages">Static and Dynamic Programming Languages</h1>
<p>Here you won’t find the programming languages in both categories. If a programming language is static by nature, it remains Static and vice versa. In the previous section of High-Level programming languages, we talked about the structure of the code and programming languages can support multiple such approaches. But here, it is based on compile-time and runtime. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643971148123/IvLmLojSQ.png" alt="4_20220204_144017_0003.png" /></p>
<h2 id="heading-static-programming-languages">Static Programming Languages</h2>
<p>In statically typed programming languages, we specify the data type of the variable. For example, <code>int a = 12;</code> or <code>string wealth = “cars”;</code>. We do this because the compiler checks all details of variables. And a variable cannot have two data types, or the code won’t compile and convert to machine language in a Static Programming Language System. </p>
<p>For example, if the variable <code>string wealth = “cars”;</code>, then we can’t have <code>int wealth = 24;</code> at the same time because the compiler will show an error. </p>
<p>The error will also show an error if we write <code>int wealth = “car”;</code> because here the datatype declared is an integer but, the value assigned is a string. The compiler will show the syntax error before compiling. </p>
<h3 id="heading-the-advantages-of-using-static-programming-languages">The Advantages of using Static programming languages</h3>
<p>We have more control over the code. We can remove all syntax errors even before the source code goes for compilation. That saves a lot of time and energy that may go into debugging. Static programming languages are comparatively faster at runtime as the compiler translates all the code before running.</p>
<p><strong>Examples of Static Programming Languages:</strong> Java, C++, C#, C, Pascal, Go, Kotlin, Swift, Haskell, Fortran, Scala</p>
<h2 id="heading-dynamic-programming-languages">Dynamic Programming Languages</h2>
<p>In Dynamically typed programming languages, we do not specify the variable datatype. For example, we can write like <code>a = 12</code> or <code>wealth = “cars”</code>. In a Dynamic Programming Language, the datatype checking happens at runtime, when the program is running as machine code in the form of 0s and 1s.</p>
<p>If you write <code>a = 3</code> and <code>a = “word”</code> in the same code, a Dynamic Programming Language will not show an error when compiling. The computer will show an error when the code is running (at runtime as machine code).</p>
<h3 id="heading-the-advantages-of-using-dynamic-programming-languages">The Advantages of using Dynamic Programming Languages</h3>
<p>We have to write a lot less code comparatively as we don’t have to deal with datatype specifications. But might give errors at runtime. But that does not bother programmers as dynamic programming languages are faster to write, easy to understand and more flexible. That makes bug finding easier. </p>
<p><strong>Examples of Dynamic Programming Languages:</strong> Python, JavaScript, Ruby, PHP, Ruby, Lua, Perl </p>
<p>Thanks for reading! Let me know what you understood and what you didn't. Let's connect in the comment section :)</p>
]]></content:encoded></item></channel></rss>