<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Madushanka Kahawa on Medium]]></title>
        <description><![CDATA[Stories by Madushanka Kahawa on Medium]]></description>
        <link>https://medium.com/@madushankakahawa?source=rss-6d80b13ee4b1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*kRDdxYw_aXdFCcPC.jpg</url>
            <title>Stories by Madushanka Kahawa on Medium</title>
            <link>https://medium.com/@madushankakahawa?source=rss-6d80b13ee4b1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:28:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@madushankakahawa/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding Child Processes in Node.js — A Practical Overview]]></title>
            <link>https://medium.com/@madushankakahawa/child-process-in-node-js-501326921d49?source=rss-6d80b13ee4b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/501326921d49</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[child-processes]]></category>
            <dc:creator><![CDATA[Madushanka Kahawa]]></dc:creator>
            <pubDate>Sun, 25 Aug 2024 19:19:03 GMT</pubDate>
            <atom:updated>2025-11-12T05:28:38.031Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sw8QyNRfS0owEmswY1yc4A.png" /></figure><p>When I started exploring <strong>Node.js</strong>, one of the most powerful concepts I came across was the <strong>child process</strong>. It allows the main (parent) process to spawn separate processes that can run independently, enabling true parallel execution. Each child process has its own memory space, execution context, and system resources.</p><p>In Node.js, this capability is provided through the <strong>child_process module</strong>, which lets us create and manage these subprocesses. It’s especially useful for performing <strong>I/O-bound</strong> or <strong>CPU-intensive</strong> tasks without blocking the main event loop. Communication between the parent and child processes happens through standard streams (stdin, stdout, stderr) or an <strong>Inter-Process Communication (IPC)</strong> channel.</p><h3>Why Use Child Processes</h3><ul><li>Executing system commands</li><li>Running scripts</li><li>Launching external applications</li><li>Performing CPU-intensive tasks</li></ul><p>By using separate processes, I can keep the main thread responsive while delegating heavy or long-running work to a background process.</p><h3>Methods of Creating Child Processes</h3><p>Node.js offers four main methods to create child processes:</p><ol><li><a href="#cf81">spawn</a>(command, args, options)</li><li><a href="#ee19">exec</a>(command, options, callback)</li><li><a href="#1022">execFile</a>(file, args, options, callback)</li><li><a href="#118b">fork</a>(modulePath, args, options)</li></ol><ul><li>Returns ChileProcess instance that can use standard stream to communicate between parent process and child process.</li><li>These methods create processes asynchronously, meaning the parent process does not wait for the child process to complete.</li></ul><h3>spawn(command, args, options)</h3><p>The spawn() method launches a new process using the given command and arguments. It streams data in real time, making it ideal for tasks that require <strong>continuous output</strong> — such as watching file changes or handling logs.</p><p><strong>Use cases:</strong></p><ul><li>Real-time data processing (e.g., running tail -f on a log file)</li><li>Streaming data</li></ul><p>High security (shell not involve by default).</p><h3>exec(command, options, callback)</h3><p>The exec() method runs a command in a shell and buffers the entire output before returning it through a callback. It’s very convenient for executing shell commands directly.</p><p>Use Cases:</p><ul><li>Running commands like<br> mkdir test &amp;&amp; cd test &amp;&amp; echo &quot;Hello&quot; &gt; file.txt (spawns a shell and runs the command within that shell).</li><li>When I need the complete output once the command finishes.</li></ul><p>However, since exec() uses a shell by default, it’s important to sanitize user input to prevent <strong>shell injection attacks</strong>.</p><h3>excecFile(file, args, options, callback)</h3><p>execFile() is similar to exec(), but it runs an executable file directly — <strong>without spawning a shell</strong>. This makes it safer and slightly faster.</p><p>Use Cases:</p><ul><li>Running scripts or executables (like Python or bash scripts) without shell commands.</li></ul><p>Not designed for shell commands. Similar to exec but specifically designed to execute scripts directly, without involving a shell by default. Since it does not spawn a shell, it reduces the risk of shell injection attacks, making it slightly faster and less resource-intensive than exec.</p><h3>fork(modulePath, args, options)</h3><p>The fork() method is designed specifically for running other Node.js scripts. It automatically creates an <strong>IPC channel</strong>, allowing easy message passing between the parent and child.</p><p>Use Cases:</p><ul><li>Running another Node.js module as a separate process.</li><li>Ideal for background computation or distributed processing.</li></ul><h3>Common Child Process Events</h3><ul><li>close — Triggered after the process ends and its streams close.</li><li>disconnect — Emitted after manually disconnecting an IPC channel.</li><li>error — Fired when spawning fails or communication errors occur.</li><li>exit — Indicates the process has finished running.</li><li>message — Emitted when using process.send() for IPC communication.</li><li>spawn — Triggered when the child successfully starts.</li></ul><h3>Useful Options</h3><h4>common options</h4><ul><li><strong>cwd</strong>&lt;string&gt; — current working directory</li><li><strong>env</strong>&lt;Object&gt; — Environment key-value pair. Default: process.env</li><li><strong>uid</strong>&lt;number&gt; — user identity (Unix-like operating systems including Linux, macOS)</li><li><strong>gid</strong>&lt;number&gt; — group identity (Unix-like operating systems including Linux, macOS)</li><li><strong>timeout</strong>&lt;number&gt; — Used to control how long the child process is allowed to run</li><li><strong>signal</strong>&lt;AbortSignal&gt; — Used to specify a signal that should be sent to the parent process when the child process is terminated</li><li><strong>killSignal</strong>&lt;string|integer&gt; — Option specifies the signal that should be used to terminate the child process when calling the kill() method on the child process object. (e.g., SIGTERM, SIGKILL)</li><li><strong>shell</strong>&lt;boolean&gt; — True or false value (not applicable for fork)</li><li><strong>windowsHide </strong>— Hide the sub process console window that would normally be created on Windows systems (not applicable for fork)</li></ul><h4>exec/execFile related options</h4><ul><li><strong>encoding</strong>&lt;string&gt; — The encoding used for all stdio inputs and outputs. Default: ‘utf8’</li><li><strong>maxBuffer</strong>&lt;number&gt; — Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated, and any output is truncated</li></ul><h4>fork/spawn related options</h4><ul><li><strong>detached</strong>&lt;boolean&gt; — Prepare the child to run independently of its parent process. Setting options.detached to true makes it possible for the child process to continue running after the parent exits. By default, the parent waits for the child to exit. To avoid that, use subprocess.unref().</li><li><strong>stdio </strong>— Used to configure the pipes that are established between the parent and child processes.</li><li><strong>serialization</strong> — Specifies the kind of serialization used for sending messages between processes (json, advanced).</li></ul><h4>fork related option</h4><ul><li><strong>execPath</strong>&lt;string&gt; — Executable used to create the child process.</li><li><strong>execArgv</strong>&lt;string[]&gt; — List of string arguments passed to the executable. Default: process.execArgv.</li><li><strong>silent</strong>&lt;boolean&gt; — If set to true, stdin, stdout, and stderr of the child will be piped to the parent; otherwise, they will be inherited from the parent.</li></ul><h4>spawn related option</h4><ul><li><strong>argv0</strong> — Value of argv[0] sent to the child process.</li></ul><h3>Explanation with use cases</h3><h4>Real time data handeling</h4><p>example: running tail -f command in child process</p><ul><li>most suitable method is <strong>spawn.</strong></li><li>Because it has direct access to stdin stream.</li><li>spawn does not buffer the output until process terminate.</li><li>exec — is not suitable because it buffer all out put and send it to parent process one time. Also it increase the memory usage in parent process.</li><li>execFile — also not suitable. It behave same as exec.</li><li>fork — is design for IPC communication. The IPC mechanism is for exchanging messages, not for handling large, continuous data streams.</li></ul><h4>Execute shell commands</h4><p>Example: mkdir testDir &amp;&amp; cd testDir &amp;&amp; echo &quot;This is a test file&quot; &gt; test.txt &amp;&amp; dir</p><ul><li>Best meth is <strong>exec</strong>, because automatically used shell to run command. Also ne need config env.</li><li>with spawn we need to specified the cmd.exe in windows or /bin/sh on Unix-based systems.</li><li>with execFile, command run without shell. to run shell specified command need to enable shell. (execFile not design for shell commands)</li><li>fork method is not suitable. its only design for execute node module as child process.</li></ul><h4>Run executable file without shell</h4><p>Example: execute python script without involving a shell</p><ul><li>most suitable methos is <strong>execFile</strong>. because with that methda shell is false by default.</li><li>spawn sloso can used, shell is false by default.</li><li>exec method also can used. with that have security risk. shell injection can happen when we use unsanitized use input as command.</li><li>fork only suitable for node nodule. if that script is non node fork is not suitable.</li></ul><h4>Run Node.js module with IPC</h4><ul><li>most suitable method is <strong>fork</strong>. its desing for execute node modules in child process. And it automatically setup IPC channel and easy to communicate between parent process and child process.</li><li>exec, spawn can used but lacks the IPC capabilities.</li></ul><p><strong>Special Note — </strong>Avoid using unsensitized user input with shell commands. Doing so can lead to shell injection vulnerabilities.</p><h3>Debugged Child Process</h3><ul><li>When I need to debug a child process, I use Node’s built-in inspector tools</li></ul><h4>Step 1</h4><ul><li>Start the Node.js process with the --inspect or --inspect-brk flags. This will open a debugging port.</li></ul><pre>node --inspect-brk index.js<br>// This command will start the Node.js process with the debugger and pausepauses the execution on the first line.</pre><pre>node --inspect index.js<br>// This command will start the Node.js process with the debugger, but it won&#39;t pause at the first line.</pre><h4>Step 2</h4><p>Open Chrome and go to chrome://inspect.</p><h4>Step 3</h4><ul><li>Click on “Open dedicated DevTools for Node”</li><li>The default port for Node.js debugging is <strong>9229</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*FO6dsokxHGqUUIk03Tm0UQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=501326921d49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practices for Securing Sensitive Information in Source Code]]></title>
            <link>https://medium.com/@madushankakahawa/best-practices-for-securing-sensitive-information-in-source-code-917d1510d87e?source=rss-6d80b13ee4b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/917d1510d87e</guid>
            <category><![CDATA[environment-variables]]></category>
            <category><![CDATA[secure-information]]></category>
            <category><![CDATA[vulnerability]]></category>
            <category><![CDATA[encryption-in-code]]></category>
            <category><![CDATA[pipeline]]></category>
            <dc:creator><![CDATA[Madushanka Kahawa]]></dc:creator>
            <pubDate>Sat, 10 Aug 2024 23:17:43 GMT</pubDate>
            <atom:updated>2024-08-10T23:17:43.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pCqvWE0GCqOTOA2s.png" /></figure><h3>Background</h3><p>We have integrated Snyk tool for detecting vulnerabilities within codebases and enhancing project security. During our analysis, Snyk identified a critical issue: the presence of hard-coded secret keys in our project. Hard-coding sensitive information such as secret keys can expose our application to significant security risks, including unauthorized access and data breaches.</p><p>This article explores various strategies to securely manage and protect these secret keys. By implementing these best practices, we can mitigate the risks associated with hard-coded secrets and significantly enhance the overall security of our project.</p><p>sensitive information — secrte key for cryptoraphy, credentional for db, and api. etc</p><h3>Reasons for Not Storing Sensitive Information in Source Code</h3><ul><li>Open Source Projects — If the project is open source, anyone can access the source code, including any sensitive information.</li><li>Private Projects with Multiple Developers — Even in private projects, multiple developers are often involved. While they need access to the source code, they do not necessarily need access to sensitive information like API keys or credentials.</li><li>Project Growth — A project that starts with a single developer might eventually grow, involving many contributors as it matures.</li><li>Risk of Misuse — If sensitive information falls into the wrong hands, whether intentionally or accidentally, it can be misused, leading to potential security breaches, data leaks, or unauthorized access to systems.</li></ul><p>Therefore Keeping this information out of the codebase minimizes the risk of accidental exposure.</p><h3>Methods of removing hard code sensitive information from source code</h3><h4>Use environment variable</h4><p>Let’s take a Node.js application on the Windows platform. We can set environment variables in several ways.</p><ul><li>Set Environment Variable and Run Application</li><li>Pass Variables as Command Line Arguments and Set Environment Variables in the Application</li><li>Set Permanent Environment Variables</li><li>Maintain Environment Variables Through a File</li></ul><blockquote><strong>Set Environment Variable and Run Application</strong></blockquote><p>We can set an environment variable and run the application in a single command.</p><pre>// CMD<br>set MY_KEY=secret_key &amp;&amp; node app.js</pre><p>In this example, the MY_KEY variable is set in the environment temporarily (until the command prompt session ends), and then the Node.js application is run.</p><p>This is the recommended way because there’s no need to write extra code in the application to store the environment variable.</p><blockquote><strong>Pass Variables as Command Line Arguments and Set Environment Variables in the Application</strong></blockquote><p>We can pass variables as command line arguments and set them within the application.</p><pre>// CMD<br>node app.js MY_KEY=secret_key</pre><pre>// app.js<br>const myKeyArg = process.argv.find(arg =&gt; arg.startsWith(&#39;MY_KEY=&#39;));<br><br>if (myKeyArg) {<br>  const myKey = myKeyArg.split(&#39;=&#39;)[1];<br>  process.env.MY_KEY = myKey;<br>}</pre><p>This method is compatible with different platforms.</p><blockquote><strong>Set Permanent Environment Variables</strong></blockquote><p>We can set a permanent environment variable using the setx command.</p><pre>// CMD<br>setx MY_KEY secret_key</pre><p>This is not the recommended way. It can cause issues if you are using a shared instance.</p><p>setx does not affect the current session but will apply to new command prompt sessions.</p><blockquote><strong>Maintain Environment Variables Through a File</strong></blockquote><p>We can create a .env file that contains environment variables and load these variables into the application. Use the dotenv package to handle this.</p><pre>// .env<br>MY_KEY=secret_key<br>DB_HOST=localhost<br>DB_PORT=5432</pre><p>As a best practice, ensure that this .env file is not committed to source control. Instead, use a README file or a .env.sample file (without actual values) to communicate which environment variables are required.</p><blockquote><strong>Accessing these envirment varible</strong></blockquote><p>in Node.js we can access enviroment varible as follow app.js</p><pre>const myKey = process#v.MY_KEY;<br>console.log(&#39;MY_KEY environment key : &#39;, myKey);</pre><h4>Use CI/CD Pipelines</h4><blockquote><strong>GitHub</strong></blockquote><p>If we are using GitHub Actions, we can store sensitive information as secrets at the repository, organization, or environment level. These secrets are encrypted and are only available within the workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MZyTxgh1O9nHwr_mbVtJIQ.png" /></figure><p>In our GitHub Actions, we can set environment variables as follows:</p><pre>- name: Set environment variables<br>  run: echo &quot;API_KEY=${{ secrets.API_KEY }}&quot; &gt;&gt; $GITHUB_ENV</pre><p>Inside our project, we can access these variables as process.env.API_KEY.</p><blockquote>B<strong>itbucket</strong></blockquote><p>Similar to GitHub, if we use Bitbucket Pipelines, we can store sensitive information as variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kb6GNtQN-9tz4aNcCeCd0g.png" /></figure><p>If we mark them as secure, their values will be masked.</p><blockquote><strong>Bamboo</strong></blockquote><p>Bamboo and Bitbucket are both products from Atlassian. Bamboo is a CI/CD tool.</p><p>Secrets can be set at the repository level, and their values are masked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*06ah1WWFSDaX4kMe6HelRA.png" /></figure><p>We can also override these variables at the branch level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*109uKsHttwXmqAmFlYXp4Q.png" /></figure><p>These variables can be accessed in the application using process.env.API_KEY.</p><h4>Use Secret Management Tools</h4><p>Secret management tools are used to securely store and manage project secret keys. These tools provide features like automatic rotation, auditing, and fine-grained access control.</p><ul><li>AWS Secrets Manager</li><li>Azure Key Vault</li><li>Google Cloud Secret Manager</li></ul><p>Example in AWS</p><pre>const AWS = require(&#39;aws-sdk&#39;);<br>const secretsManager = new AWS.SecretsManager();</pre><pre>async function getSecret() {<br>    const data = await secretsManager.getSecretValue({ SecretId: &#39;API_KEY&#39; }).promise();<br>    const apiKey = data.SecretString;<br>    console.log(apiKey);<br>}</pre><pre>getSecret();</pre><h4>Use Configuration Management Tools</h4><p>We can use tools like Ansible, Chef, or Puppet to inject secrets into the application environment during the deployment process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=917d1510d87e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Future of User Interface Design]]></title>
            <link>https://medium.com/@madushankakahawa/future-of-user-interface-design-ffd304a6ed54?source=rss-6d80b13ee4b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffd304a6ed54</guid>
            <dc:creator><![CDATA[Madushanka Kahawa]]></dc:creator>
            <pubDate>Tue, 05 Apr 2022 13:21:09 GMT</pubDate>
            <atom:updated>2022-04-05T13:53:51.519Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TdenELvQApb7f3uU24UbmA.jpeg" /></figure><h3>What is the <strong>User interface?</strong></h3><p>The user interface is the way that we used to interact with the computer systems. Before the UI people use CLI to interact with computer systems. The concept of UI design first emerged when GUI operating systems such as Macintosh and Microsoft entered the market. From time to time based on the user expectation, GUI was rapidly evolved. And it makes it easy for the user to interact with the computer system and improve the user exeperience. Still, UI has too long a way to go and in this article, we discussed the future UI design.</p><h3>Different user interface designs in future</h3><ol><li><strong>The Metaverse</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*Ch_TRWZp-4vX9WSec_IY2A.png" /></figure><p>Metaverse means the combination of different technologies like virtual reality(VR), augmented reality(AR), and video where users “live” within a digital universe.</p><p><strong><em>2. Gesture Recognition</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2WyqcHz9MCvmIlu_-Sl-2w.jpeg" /></figure><p>Gesture recognition Interfaces (GRI)are interfaces that are controlled by hand movements or touch. It completely eliminates physical contact with a device directly as by touching or indirectly via a secondary device like a mouse. In today’s tech world, gesture-based UI has gone a long way and is gaining traction in the future of user interface design. GRI takes inputs by reading body movement using the camera and sensor. Example GUI read the direction of the handle movement. GRI systems are used in games, video players, etc...</p><p><strong><em>3. Voice User Interface</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*QYmAFPadOnm3Dy1tcbc9QA.png" /></figure><p>Voice User Interface allows users to interact with a system through speech commands. Examples of VUI are virtual assistants, such as Siri, Google Assistant, and Alexa. With the better machine learning capability, the VUI comonad is now similar to human language. The advantage of VUI is work with voice interfaces is faster and saves time. For example, while we working on something we can provide voice commands without holding the current task.</p><p><strong>4. V<em>irtual Reality</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aAuotxHRUvpiYWg37Ak1fQ.png" /></figure><p>Virtual Reality (VR) is a computer-generated environment with scenes and objects that appear to be real, making the user feel they are immersed in their surroundings. Virtual Reality creates a three-dimensional artificial environment. The virtual environment is designed to give the user the impression that they are in a real place. Some of the applications of virtual reality can include entertainment (gaming) and educational purposes (Medical etc). These systems use either VR headsets or multi-projected environments to generate realistic images, sounds, and other sensations that simulate a user’s physical presence in a virtual environment.</p><p><strong><em>5. Augmented Reality</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tkUW4Q8nKsdt9nrzoRC8kQ.jpeg" /></figure><p>Augmented reality is an experience where designers enhance parts of users’ physical world with computer-generated input. It provides an interactive experience of a real-world environment where the objects that reside in the real world are enhanced by computer-generated perceptual information, sometimes across multiple sensory modalities, including visual, auditory, and haptic.</p><p>Example: <em>Google translate</em></p><h3>Next Generation UI Design Tools</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kllsG8KPtzwxxSlsRPzX7Q.png" /></figure><p>UI design tools have come a long way since the first generation of Adobe Photoshop, a program intended for editing photos, not creating dynamic user interfaces. The current generation of tools, such as Adobe XD, Figma, and Sketch, have made our jobs easier and faster.</p><p>Future user interface tools will combine design and coding to provide designers and developers with a more satisfying experience. Using HTML and CSS is not easy to create UI for big protect even if they are familiar with it. The developer does not have to do a lot of work in creating UI design because of next-generation design tools that interface with source code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*Xte947_oSF01y1YsfmUgPA.jpeg" /></figure><p>To produce design components, current technologies rely on proprietary programming models. These models aren’t as strong as CSS, and they don’t let designers see the auto-generated code that lies behind their design files — code that must be exported to HTML, CSS, or JavaScript at some point. It would be a lot easier if our tools supported HTML and CSS right out of the box.</p><p>Next-gen design tools will interface with the source code directly, eliminating throwaway deliverables, and enabling designers and developers to collaborate on the same deliverable: the source code.</p><h3>UI’s impact on everyday life</h3><p>In this article, we look at different user interface designs and next-generation UI design tools. Now we check how these Ui impact on everyday life</p><p>As we discussed above in voice interface, If we are using a voice interface system in our day-to-day life our time effort will be saved. As an example, if we use VUI for answering phone calls. While we are on some work and we received the call. If we used VUI we don&#39;t need to hold our task to answer calls. We can answer that call while continuing our work.</p><p>Also if we use the Gesture Recognition interface we can save time. HOW? let&#39;s assume our TV has the gesture recognition interface, and we want to do something using the TV we don&#39;t need a remote or not need to reach the physical location of the TV. We can simply do that by moving our hands.</p><p>If we use v<em>irtual reality for learning purposes. We can get a greater knowledge from this rather than 2n images. We can get a clear idea by looking 3d images. Not only this, others several impacts on our life because of UI.</em></p><p>Up to now, we have discussed what is UI, different UI design in the future, next-generation UI design tool, and how UI impact our everyday life. Hope you understand.</p><p>Thank You.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffd304a6ed54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Licensing]]></title>
            <link>https://medium.com/@madushankakahawa/software-licensing-dbcb57639964?source=rss-6d80b13ee4b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbcb57639964</guid>
            <dc:creator><![CDATA[Madushanka Kahawa]]></dc:creator>
            <pubDate>Tue, 08 Sep 2020 16:52:36 GMT</pubDate>
            <atom:updated>2020-09-08T20:26:26.067Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*OEdTZLm22LYHliP5u-vX5A.png" /></figure><h3>Software Licensing?</h3><blockquote>A software license is a document that provides legally binding guidelines for the use and distribution of software.</blockquote><p>In simple words, Software Licensing is an agreement between customer and owner of that software. Software licenses can impose restrictions on how the software can be used. End-user can use one or many copies of software or can use some parts of the software or can modify the software, that depends on the software license.</p><h3>Types of software licenses</h3><p>There are five types of common software license models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*RREOQbauF_TIw-7NYbBhsA.jpeg" /></figure><ol><li><strong>Public domain</strong></li><li><strong>Permissive</strong></li><li><strong>LGPL</strong></li><li><strong>Copyleft</strong></li><li><strong>Proprietary</strong></li></ol><h3><strong>Public domain </strong>licenses</h3><p>The public domain is the most permissive type of software license. When software is in the public domain, anyone can modify and use the software without any condition. In other words, Public domain software is any software that has no legal, copyright, or editing restrictions associated with it. That is free and open-source software that can be publicly modified, distributed without any restrictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*VrEcdlSjAM5tAmVGZP9leQ.png" /></figure><ul><li>WTFPL license</li><li>Zero/public domain (CC0)</li><li><a href="https://en.wikipedia.org/wiki/Unlicense">Unlicense</a></li></ul><h3><strong>Permissive </strong>licenses</h3><p>Permissive licenses are also known as Apache License, BSD license, or MIT license. Permissive licenses have larger compatibility than protective ones, which cannot be blindly combined and mixed. It contains minimal requirements about how the software can be modified or redistributed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*kjCBvj_nUEp-V_CiE_Dn5A.jpeg" /></figure><ul><li>Apache license</li><li>BSD license</li><li>MIT license</li></ul><h3><strong>LGPL l</strong>icenses</h3><p>A Lesser General Public License (LGPL) is a license for open-source software that allows for provisions for including elements of free software in either free or proprietary software. If you simply compile or link an LGPL-licensed library with your own code, you can release your application under any license you want, even a proprietary license. A Lesser General Public License provides less of a standard for source code analysis, but there are still requirements for transparency and attribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1MOWYvrIx5BufDkih87yzA.png" /></figure><ul><li>GNU Library General Public License</li></ul><h3><strong>Copyleft licenses</strong></h3><p>Copyleft licenses are also known as reciprocal licenses or restrictive licenses. The most well-known example of copyleft or reciprocal license is the GPL. These licenses allow you to modify the licensed code and distribute new works based on it, as long as you distribute any new works or adaptations under the same software license. For example, a component’s license might say the work is free to use and distribute for personal use only. So any derivative you create would also be limited to personal use only.</p><p>What makes it special is that users of your software have the right to change the code. Therefore, you need to get your own source code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Dg5UBbmNw1SPXuhCMSJ9jA.png" /></figure><ul><li>GNU General Public License</li><li>Mozilla Public License</li><li>Eclipse Public License</li><li>Microsoft Reciprocal License</li><li>Mechanical</li></ul><h3><strong>Proprietary l</strong>icenses</h3><p>Proprietary licenses are the most restrictive software licensing domain of all types. The idea behind it is that all rights are reserved. It is generally used for proprietary software where the work may not be modified or redistributed.</p><ul><li>NetBeans</li><li>Windows</li><li>Spotify</li><li>xSplit</li></ul><h4>most common open-source licenses</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rfiIvEAqZNVsXAhiypa0YA.jpeg" /></figure><ul><li>MIT, 25%</li><li>GPL 3.0, 19%</li><li>Apache 2.0, 15%</li><li>GPL 2.0, 15%</li><li>BSD 3, 6%</li><li>LGPL 2.1, 6%</li><li>Ms-Pl, 5%</li><li>BSD 2, 3%</li><li>Zlib, 1%</li><li>Eclipse 1.0, 1%</li><li>BSD 4, 1%</li><li>Other, 5%</li></ul><h4>Reference</h4><p><a href="https://www.synopsys.com/blogs/software-security/5-types-of-software-licenses-you-need-to-understand/">Five types of software licenses you need to understand</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbcb57639964" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethical Whistleblowing]]></title>
            <link>https://medium.com/@madushankakahawa/ethical-whistleblowing-3686ea32a562?source=rss-6d80b13ee4b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3686ea32a562</guid>
            <category><![CDATA[whistleblowing]]></category>
            <dc:creator><![CDATA[Madushanka Kahawa]]></dc:creator>
            <pubDate>Sat, 25 Jul 2020 17:39:20 GMT</pubDate>
            <atom:updated>2020-07-25T19:36:59.567Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*5xW7SdJW5OyBjN8ojDysMQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*YL9RFU7tBBAr-73DScwd6w.jpeg" /></figure><p>Whistle- It is a tool that use to make sound</p><h3><strong>What is whistleblowing?</strong></h3><p>It is a concept of exposure by people withing an organization regarding an illegal or unethical activity or significant maladministration activity.</p><p>Example: A company or organization reads user emails, hears to call, but the user doesn’t know about this. People inside the company or organization (maybe an employee, supplier, or customer ) know about that and they expose all social about the situation to provides benefits for the user.</p><p>The whistleblower should have supporting reasons for claiming that the activities of the agency or company are wrong.</p><p><strong><em>Types of Whistleblowing</em></strong></p><ol><li><em>Internal whistleblowing</em></li><li><em>Personal whistleblowing</em></li><li><em>External whistleblowing</em></li></ol><h4>Before you blow the whistle:</h4><ul><li>Seek legal advice, other advice</li><li>Make sure you have all facts and if possible, proof</li><li>Plan the method of disclosure</li><li>Be prepared to be ignored, even victimized</li></ul><h3><strong>Elements of ethical whistleblowing.</strong></h3><p>There are four elements of the whistle-blowing process</p><blockquote>The whistle-blower</blockquote><blockquote>The whistle-blowing act or complaint</blockquote><blockquote>The party to whom the complaint is made</blockquote><blockquote>The organization against which the complaint is lodged</blockquote><h3>procedure for whistleblowing.</h3><ol><li><strong>Hire a powerful Attorneys</strong></li></ol><p>Hire a skilled lawyer with experience in handling whistle blower claims can advice legally to gather evidence against the employer and protect professional reputation.</p><p><strong>2. Make sure you have evidence</strong></p><p>The government will not pay you a reward for bringing them questionable gossip of misdeeds, but rather specific proof, such as emails, internal studies, billing records, test results, names, contact information of involved parties, and other forms of documentary evidence.</p><p><strong>3. File a complaint</strong></p><p>Whistleblowers must file a complaint in court and submit it to the federal government with a Disclosure Statement that details the suspected misconduct.</p><p><strong>4. Play the waiting game</strong></p><p>If the government should decide to proceed forward with your case, it is important to be patient.</p><p><strong>5. Prepare to be “outed”</strong></p><p>You have to prepare yourself to be “outed” and the consequences that it may bring. It’s recommended to search for a new job as soon as possible after filing a whistleblower claim.</p><p><strong>6. Be prepared to testify</strong></p><p>f the government decides to take action against your employer based on the results of its investigation, you may be asked to testify at a grand jury proceeding or during the trial. You must be prepared to reveal your identity, since your testimony may have a considerable impact on the outcome of the case.</p><p><strong>References</strong></p><p><a href="https://www.attorneymahoney.com/blog/2016/july/a-guide-to-whistleblowing-claims-in-washington-d/">A Guide to Whistleblowing Claims in Washington, D.C.</a></p><p><a href="https://www.ethicssage.com/2015/07/is-whistleblowing-a-moral-act.html#:~:text=There%20are%20four%20elements%20of,somewhat%20analogous%20to%20civil%20disobedience">https://www.ethicssage.com/2015/07/is-whistleblowing-a-moral-act.html#:~:text=There%20are%20four%20elements%20of,somewhat%20analogous%20to%20civil%20disobedience</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3686ea32a562" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple REST API with Node.js]]></title>
            <link>https://medium.com/@madushankakahawa/simple-rest-api-with-node-js-51bb357fff0a?source=rss-6d80b13ee4b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/51bb357fff0a</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Madushanka Kahawa]]></dc:creator>
            <pubDate>Fri, 10 Jan 2020 16:10:08 GMT</pubDate>
            <atom:updated>2020-03-19T21:36:56.023Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GPQ7MDPCOdpdJSXP2f3Jjw.png" /></figure><p><strong>What is API ?</strong></p><ul><li>It is an Application Programming Interface that allows two applications to talk to each other.</li><li>API is a communication protocol to talk to each other</li></ul><p><strong>Rest API</strong></p><p>Rest (Representational State Transfer) API is Web service(system/software that uses an address ex: URL in World Wide Web) API. We can send data and receive data using a specific URL. These URLs called <strong>Request </strong>and receive data called <strong>Respond.</strong></p><p><strong>HTTP Methods for rest API</strong></p><ul><li>POST — for send data</li><li>GET — for request data</li><li>DELETE — for delete data</li><li>PUT — for update / replace data</li><li>PATCH — for update / modify data</li></ul><h3>Let’s start</h3><ol><li>Create a node app</li></ol><p>Open a command prompt and type</p><pre>mkdir node_app<br>cd node_app</pre><p>for initializing app</p><pre><strong><em>npm init</em></strong></pre><p>After that, you can see the package.json file. Then create index.js file</p><p>index.js</p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br>const port = process.env.PORT || 5000;<br>app.use(express.json({<br>    extended:true<br>}));</pre><pre>app.listen(port,() =&gt; {<br>    console.log(`app start ${port}`);<br>});</pre><p>add MongoDB connection</p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br>const port = process.env.PORT || 5000;<br>app.use(express.json({<br>    extended:true<br>}));</pre><pre><strong>const mongoose = require(‘mongoose’);<br>mongoose.connect(&quot;  Your mongoDB connection  &quot;);<br>const usertRoutes = require(‘./routs/users’);<br>const productRoute = require(‘./routs/product’);</strong></pre><pre>app.listen(port,() =&gt; {<br>    console.log(`app start ${port}`);<br>});</pre><p>user.js model class</p><pre>const mongoose = require(&#39;mongoose&#39;);</pre><pre>const userSchema = mongoose.Schema({<br>    name: { type: String , required : true},<br>    age: { type: Number , required : true },<br>    email: { type:String , required:true},<br>    userImage: { type:String },<br>    password: {type:String , required: true}<br>});</pre><pre>module.exports = mongoose.model(&#39;user&#39;, userSchema);</pre><p>let’s create user.js router class</p><pre>const express = require(&#39;express&#39;);<br>const router = express.Router();</pre><pre>router.post(&#39;/&#39;,(req,res)=&gt;{<br>  user.find({email:req.body.email},(error , result)=&gt;{<br>    if(result.length == 0){<br>      user.create({<br>        name:req.body.name,<br>        age:req.body.age,<br>        email:req.body.email,<br>        password:hashValue<br>      } , (error , user) =&gt; {<br>        if(user){<br>          return res.json(user);<br>        }else{<br>          return res.json({&quot;message&quot;:error});<br>        }<br>      })<br>    }else{<br>      return res.json({&quot;message&quot;:&quot;Email exits&quot;});<br>    }<br>  });<br>});</pre><pre>router.get(&#39;/&#39;,(req,res)=&gt;{<br>  user.find({} , (error , users) =&gt; {<br>    if(error){<br>      return res.json(error);<br>    }else{<br>      return res.json({<br>        &quot;length&quot;: users.length ,<br>        &quot;users&quot; : users<br>      });<br>    }<br>  });<br>});</pre><pre>router.get(&#39;/:userId&#39;,(req,res)=&gt;{<br>  var id = req.params.userId;<br>  user.findById(id , (error , user) =&gt;{<br>    if(error){<br>      return res.json(error);<br>    }else{<br>      if(user){<br>        return res.json(user);<br>      }else{<br>        return res.json({&quot;message&quot; : &quot; no valid value&quot;});\<br>      }<br>    }<br>  });<br>});</pre><pre>router.delete(&#39;/:userId&#39;,(req,res)=&gt;{<br>  var id = req.params.userId;<br>  user.deleteOne({_id : id}, (error , dele) =&gt; {<br>    if(error){<br>      return res.json(error);<br>    }else{<br>      if(dele.deletedCount == 0){<br>        return res.json({&quot;message&quot; : &quot;Not found&quot;});<br>      }else{<br>        return res.json({&quot;message&quot; : &quot;sussess&quot;});\<br>      }<br>    }<br>  })<br>});</pre><pre>router.patch(&#39;/:userId&#39;,(req,res)=&gt;{<br>  var id = req.params.userId;<br>  user.update({_id : id},{$set:{name:req.body.name}}, (error , update) =&gt; {<br>    if(error){<br>      return res.json(error);<br>    }else{<br>      if(update.nModified == 0){<br>        return res.json({&quot;message&quot; : &quot;Not found&quot;});<br>      }else{<br>        return res.json({&quot;message&quot; : &quot;sussess update&quot;});<br>      }<br>    }<br>  })<br>});</pre><p>After adding a user router to index.js file</p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br>const port = process.env.PORT || 5000;<br>app.use(express.json({<br>    extended:true<br>}));</pre><pre>const mongoose = require(‘mongoose’);<br>mongoose.connect(&quot;  Your mongoDB connection  &quot;);<br>const usertRoutes = require(‘./routs/users’);<br>const productRoute = require(‘./routs/product’);</pre><pre><strong><em>const usertRoutes = require(&#39;./routs/users&#39;);<br>app.use(&#39;/user&#39; , usertRoutes );</em></strong></pre><pre>app.listen(port,() =&gt; {<br>    console.log(`app start ${port}`);<br>});</pre><p>2. Now you can run your app in command prompt typing node index.js command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*17Ox2IgWsvE4Tfz143DKHA.png" /></figure><p>These are the endpoint for this app</p><p>GET =&gt; <a href="http://localhost:5000/singIn/ddd">http://localhost:5000/user</a></p><p>GET =&gt; <a href="http://localhost:5000/singIn/ddd">http://localhost:5000/user</a>/10</p><p>POST =&gt; <a href="http://localhost:5000/singIn/ddd">http://localhost:5000/user</a></p><p>DELETE =&gt; <a href="http://localhost:5000/singIn/ddd">http://localhost:5000/user</a>/5</p><p>PATCH =&gt; <a href="http://localhost:5000/singIn/ddd">http://localhost:5000/user</a>/10</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51bb357fff0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write a simple Operating System]]></title>
            <link>https://medium.com/@madushankakahawa/write-a-simple-operating-system-12b8edd20af9?source=rss-6d80b13ee4b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/12b8edd20af9</guid>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Madushanka Kahawa]]></dc:creator>
            <pubDate>Sat, 15 Jun 2019 10:14:20 GMT</pubDate>
            <atom:updated>2019-06-18T07:36:22.232Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6Nc3hK98loPXP_D5GVxlw.jpeg" /></figure><blockquote>This article tells how I build a simple operating system.</blockquote><p>Before starting to build the operating system, I refer some articles. Then I get a basic idea how to create an operating system.</p><h4>What happens when the PC starts up?</h4><p>All registers are blanked and the microprocessor is set to a reset state. Then load BIOS(Basic Input Output System) and execute it.BIOS will run a necessary check of all memory for errors, connected devices like serial ports, etc. After these system checks will search for the Operating System, load it and execute. The BIOS will not load the complete operating system. It will just load a boot sector(Bootloader).</p><h3>Bootloader</h3><p>I refer JOSH — minimalOS article written on JOSH by Dr. Mohan Raj Dhanagopal and get the bootloader.asm code from it. To convert bootloader.asm file to bootloader.bin file I have setup NASM on my computer. Create bootloader.bin file using this command,</p><p>NASM bootloder.asm -o bootloader.bin -f bin</p><h3>Kernel</h3><p>The kernel is the core of the Operating System. The computer controlled by the kernel. I get kernel code from JOSH — minimalOS article written on JOSH by Dr. Mohan Raj Dhanagopal and developed the code. In the kernel file have three segments, ‘.text’ , ‘.data’ , ‘.bss’.</p><pre>    .text — code<br>    .data — initialized data (Constants)<br>    .bss — variables</pre><p>To convert kernel.asm file to kernel.bin fil</p><p>NASM kernel.asm -o kernel.bin -f bin</p><p>I add some function to the kernel file</p><ul><li>_cmd_help</li><li>_cmd_hardwareInfo</li><li>_cmd_cpuVendorID</li><li>_cmd_ProcessorType</li><li>_cmd_ProcessorSerialNo</li><li>_cmd_serialport</li><li>_cmd_MouseStatus</li></ul><h4>CPUID</h4><p>To get CPU details there have special command cpuid. These are some of this</p><p>EAX=0 (Highest Function Parameter and Manufacturer ID)</p><p>EAX=3 ( <a href="https://en.wikipedia.org/wiki/CPUID#EAX=3:_Processor_Serial_Number">Processor Serial Number</a>)</p><p>EAX=80000002h-8000004h (Processor Brand String)</p><p>For further Details about CPUID refer the link below-</p><p><a href="http://www.flounder.com/cpuid_explorer2.htm">The CPUID Explorer: Part 2</a></p><blockquote>cpuVendorID</blockquote><p>using cpuid(0) we can get cpu vendor id . Vendor id 12 bit long name and it contains ebx ,edx , ecx. I get to variable and print it using 21 interrupt service.</p><p>for example:GunuineIntel</p><p>ebx — “Genu”</p><p>ecx — “ntel”</p><p>edx — “ineT”</p><pre>mov eax,0 <br>cpuid<br>mov [strcpuid],ebx <br>mov [strcpuid+4],edx <br>mov [strcpuid+8],ecx</pre><pre><br>mov si, strcpuid  <br>mov al,0x01 <br>int 0x21 <br>ret</pre><blockquote>ProcessorType</blockquote><p>using cpuid(0x80000002 , 0x80000003 , 0x80000004) we can get processor type. Vendor id 48 bit long name and it contains eax,ebx ,edx , ecx. I get to variable and print it using 21 interrupt service.</p><pre>mov eax,0x80000002 <br>cpuid<br>mov [strcputype]   ,eax <br>mov [strcputype+4] ,ebx <br>mov [strcputype+8] ,ecx <br>mov [strcputype+12],edx  </pre><pre>mov eax,0x80000003 <br>cpuid; <br>mov [strcputype+16],eax <br>mov [strcputype+20],ebx <br>mov [strcputype+24],ecx <br>mov [strcputype+28],edx<br>  <br>mov eax,0x80000004 <br>cpuid<br>mov [strcputype+32],eax <br>mov [strcputype+36],ebx <br>mov [strcputype+40],ecx <br>mov [strcputype+44],edx  </pre><pre>mov si, strcputype           <br>mov al, 0x01 <br>int 0x21 <br>ret</pre><blockquote>ProcessorSerialNo</blockquote><p>using cpuid(3) we can get processor type. Processor serial no contains edx , ecx. I get to variable and print it using 21 interrupt service. This will not display in release mode if <strong>CPUID(0).EAX </strong>&lt; 3.</p><pre>mov eax,3 <br>cpuid<br>and edx,1 <br>mov [strcpuserno],edx; <br>mov [strcpuserno+16],ecx;<br> <br>mov si, strcpuserno  <br>mov al, 0x01 <br>int 0x21 <br>ret</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*qzskjczjJZbG7Ng4JeyxuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*31MKWEeP1Sliu9fMzpdJ5A.png" /></figure><p>I tried to make an image from the kernel.bin and bootloader.bin file. But it did not get success so that I use a .sh file in mike os to create an image. I made a bootable Pendrive and store the image in the boot sector. And Then I run the os on my laptop.</p><p>Git hub</p><p><a href="https://github.com/madushanka2016/Opererating-system">madushanka2016/Opererating-system</a></p><p>References-</p><p><a href="https://www.cs.bgu.ac.il/~yagel/dolev/MinimalOS/josh/">JOSH - Operating system tutorial</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12b8edd20af9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SEMAPHORES]]></title>
            <link>https://medium.com/@madushankakahawa/semaphores-7a73a9b6f02f?source=rss-6d80b13ee4b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a73a9b6f02f</guid>
            <category><![CDATA[semaphore]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Madushanka Kahawa]]></dc:creator>
            <pubDate>Thu, 02 May 2019 09:04:07 GMT</pubDate>
            <atom:updated>2019-05-03T08:43:22.003Z</atom:updated>
            <content:encoded><![CDATA[<p>Semaphores are integer variables that are used to solve the critical section problem by using two atomic operations wait and signal that are used for process synchronization.</p><h4>wait (Semaphores wait)</h4><blockquote>The wait operation decrements the value of its argument S, if it is positive. If S is negative or zero, then no operation is performed.</blockquote><pre>wait (Semaphores s){</pre><pre>while(s&lt;=0)</pre><pre>s--;</pre><pre>}</pre><h4>signal (Semaphores signal)</h4><blockquote>The signal operation increments the value of its argument S.</blockquote><pre>Signal(Semaphores s){</pre><pre>S++;</pre><pre>}</pre><pre>Semaphores s = new Semaphores(1);    //initialize semaphore variable to 1</pre><pre>s.acquire();                         //sem_wait()</pre><pre>//Critical Section here</pre><pre>s.release();                         //sem_post()</pre><ul><li>Assume there are two thread. When thread (1) begin run. It call to sem_wait(). Then decrements the value of its argument 1 to 0. After run critical section. The process interrupt and begging to run thread (2) , but the argument value is 0. Therefore thread (2) suspend and end the critical section in thread (1). After call sem_post() and increments the value of its argument 1. After thread (2) begging to run.</li></ul><h3>The Dining Philosopher Problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*lj0nIoI1MN-vSKHSZzgQpQ.jpeg" /></figure><h4>problem</h4><p>there are 5 philosophers sharing a circular table and they eat and think alternatively. There is a bowl of rice for each of the philosophers and 5 chopsticks. A philosopher needs both their right and a left chopstick to eat. A hungry philosopher may only eat if there are both chopsticks available. Otherwise, a philosopher puts down their chopstick and begin thinking again.</p><h4>solution</h4><pre>repeat:<br>wait(chopstick[i]);<br>wait(chopstick[(i+1) mod <br>eat<br>signal(chopstick[i]);<br>signal(chopstick[(i+1) mod 5]);<br>think<br>until false;</pre><h4>Implemented using the JAVA language</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*81XBAuZ0IQDWdSIjzxmuvg.png" /><figcaption>Main.java</figcaption></figure><p>In main java class ,</p><pre>import java.util.concurrent.Semaphore;</pre><p>This Semaphore class is implements Serializable interface.</p><p>Declaration the chopsticks array using semaphore.(line 9)</p><p>Initialize semaphore variable to 1(line 11,12,13)</p><p>Declaration philosopher array from Philosopher class(line 15)</p><p>And start running tread(line 19)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*4xqk2sx1yQ8_-H54ZVpn2g.png" /><figcaption>Philosopher.java</figcaption></figure><p>Make a thread class .Philosopher and implements Runnable. And import this,</p><pre>import java.util.Random;</pre><pre>import java.util.concurrent.Semaphore;</pre><p>Declare variable for philosopher Id ,left chopstick &amp; right chopstick. Initialize these variable using constructor. Create method for run , think , pickUpLeftChopstick , pickUpRightChopstick , eat , putChopstick.</p><ul><li>run()</li></ul><pre>public void run() {</pre><pre>try {</pre><pre>while (hungryLevel&gt;0) {</pre><pre>think();</pre><pre>pickUpLeftChopstick();</pre><pre>pickUpRightChopstick();</pre><pre>eat();</pre><pre>putChopsticks();</pre><pre>}</pre><pre>} catch (InterruptedException e) {</pre><pre>System.<em>out</em>.println(philosophersId + &quot; Philosopher was interrupted.&quot;);</pre><pre>}</pre><pre>}</pre><p>I assume philosophers have 5 hungry level. In this method call think , pickUpLeftChopstick , pickUpRightChopstick , eat , putChopstick methods.</p><ul><li>think( )</li></ul><pre>private void think() throws InterruptedException {</pre><pre>System.<em>out</em>.println(philosophersId + &quot; Philosopher is thinking.&quot;);</pre><pre>System.<em>out</em>.flush();</pre><pre>Thread.<em>sleep</em>(new Random().nextInt(10));</pre><pre>}</pre><p>In this method thread sleep random time.</p><ul><li>pickUpLeftChopstick( )</li></ul><pre>private void pickUpLeftChopstick() throws InterruptedException{</pre><pre>if(leftChopstick.availablePermits() ==0){</pre><pre>System.<em>out</em>.println(philosophersId + &quot; Philosopher is waiting for left  chopstick&quot;);</pre><pre>}</pre><pre>leftChopstick.acquire();</pre><pre>System.<em>out</em>.println(philosophersId + &quot; Philosopher is holding  left  chopstick.&quot;);</pre><pre>}</pre><ul><li>pickUpRightChopstick()</li></ul><pre>private void pickUpRightChopstick()  throws InterruptedException{</pre><pre>if(rightChopstick.availablePermits() ==0){</pre><pre>System.<em>out</em>.println(philosophersId + &quot; Philosopher is waiting for right chopstick&quot;);</pre><pre>}</pre><pre>rightChopstick.acquire();</pre><pre>System.<em>out</em>.println(philosophersId + &quot; Philosopher is holding  right   chopstick.&quot;);</pre><pre>}</pre><p>In pickUpLeftChopstick method ,if value of leftChopstick is 1 then leftChopstick.acquire() and hold the left chopstick by current philosophers. And this time leftChopstick value decrement to 0 there for any other philosopher can’t get that chopstick till the current philosopher put down.</p><p>If leftChopstick value 0 then the current philosopher can’t get that chopstick because another philosopher take that chopstick.</p><p>And the pickUpRightChopstick method , same thing happen in pickUpLeftChopstick method.</p><ul><li>eat()</li></ul><pre>private void eat() throws InterruptedException {</pre><pre>System.<em>out</em>.println(philosophersId + &quot; Philosopher is eating.&quot;);</pre><pre>System.<em>out</em>.flush();</pre><pre>hungryLevel-=1;</pre><pre>Thread.<em>sleep</em>(new Random().nextInt(10));</pre><pre>}</pre><p>The philosophers eat one time then decrements hungry level by 1. Thread sleep random time.</p><p>· putChopstick()</p><pre>private void putChopsticks() {</pre><pre>leftChopstick.release();</pre><pre>rightChopstick.release();</pre><pre>if(hungryLevel==0){</pre><pre>System.<em>out</em>.println(philosophersId + &quot; Philosopher finish eating\n&quot;);</pre><pre>}</pre><pre>System.<em>out</em>.println(philosophersId +&quot; released left and right sticks&quot;);</pre><pre>}</pre><p>this method use to release both chopstick. Then leftChopstick and rightChopstick increment the value to 1.And hungry level equal to 0 then the philosopher stop eating. Otherwise philosopher put the chopstick and think.</p><h4>Here link for github repository.</h4><p><a href="https://github.com/madushanka2016/dining-philosophers-problem">madushanka2016/dining-philosophers-problem</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a73a9b6f02f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>