Tuesday, 25 November 2014

Terminal Tweaks


As we all know Terminal is the heart of any Linux system. The newbies often find the terminal pretty boring to work on. But what if I say that you can have great fun with your terminal?

To do this, we will first learn about a file called the .bashrc, located at your home directory. This file takes care of your shell (command line) profile. The most common command line shell is the BASH, used in most of the Linux distros. General shell scripts are written to be run in BASH shells.

Any file with name preceded by a . is treated as hidden file, and hence it won't be shown generally in your file manager. In the terminal you must use ls -a to see the hidden files and directories.

The .bashrc file contains a list of commands which get executed whenever you start a terminal (bash shell). Open your terminal, and in your home directory type in cat -n .bashrc and see the output.
( cat prints the output of a text file, and -n option makes it show the line numbers as well. )



An important command, which must be mentioned here, is the alias command.
It has the general form,

alias <new command>=”<command>”

With the alias command you can give another name to a particular command.
Like, say, I type in the following and hit Enter :

alias welcome=”echo 'Hey there, how do you do?'”  

Now if I type in welcome and hit enter, the command echo 'Hey there, how do you do?' command will be executed, and hence the output:



So apparently, welcome becomes a new command. In this way you can see many aliases in the .bashrc file.

Now it is time to edit the file. Remember, you must not unknowingly delete any of the contents of the .bashrc file. It is always better to take a backup of the file.
Open the .bashrc file with any text editor, and now add the following line:

# Our own additions  


The # is used for one-line comments in BASH . The above line is for our reference, and to show that now on wards the commands are entered by the user, not by the system. Now we come to our tweaks one by one.

Advanced Copy and Move:


The first tweak is the advanced copy and move command. You must have noticed that copying or moving large files in terminal is faster, but you never get the progress of your ongoing work. The advanced copy/move commands will show you a progress command. Go to this link and follow the instructions (method 2 there is easier for newbies) . After this, your copy or move operation will look like this:



Delete with Prompt:


One of the deadliest command in Linux is the rm command. This command is used to delete a file permanently (rm means remove), without asking you for confirmation. For confirmation, you must use the -i option with rm. Many newbies confuse rm to be the rename (for renaming we use the mv command) command and hence may delete many files accidentally. I still remember, when I was a novice, I accidently deleted a movie approx 2 gigs, thinking that I am going to rename it!  So we can add this line to our .bashrc file :

alias rm=”rm -i”

Thus, now whenever you accidentally use the rm command, you get a confirmation that you are deleting the file. Thus better be safe than be sorry.



The Welcome Message:


You can make your terminal greet you whenever you open it. Just open .bashrc, add the following line at the end, and save the file:

echo “<your computer name> welcomes you, <your name>!”

e.g. in my laptop, I added:

echo “Blue-Dragon welcomes you, Vishwa Protim!”



System Information:


Another tweak which I recently found. The screenfetch command will generate your system information, with a beautiful output. First you need to type in the following commands:


mv screenFetch/ /opt/

Open .bashrc file, and add the following line at the end:

alias system='/opt/screenFetch/screenfetch-dev'

Save the file. Now reopen your terminal, and type in, system. Hit enter to see the magic.


Thus there are many such tweaks to make your Terminal experience wonderful. Also experimenting with the alias command and the .bashrc file can give you much customization. Feel free to add up your own customization here in the comment section.










Sunday, 23 November 2014

Tron-like Theme for My Qiana KDE

Hey guys, recently, I was experimenting with themes in KDE and after pretty much googling and surfing, I set off to theme and tweak my KDE desktop. Here is my new theme in Qiana KDE, and I hope you all will like it.


As you can see, it has the Tron like looks. For most of the parts, Google, Noobslab, devianart helped me along with some other websites and blogs. I am summarizing the do's here. Once again I would like to state that the designs and themes are absolutely not mine and I hold no claim on the following themes and designs.
Most of the themes can be downloaded by clicking on the Get New Themes button, right there in the settings dialog box.

Let's start from the MDM theme:


Download the Round Login HTML5 theme from the following link :

website: LinuxMint-Art.org


Now the splash screen :


Go to System Settings → Workspace Appearance and click on the Splash Screen tab. Click on the Get New Themes button and search and install NewEssenceFinal



Window Decorations :


In the Window Decorations tab click on the Get new Decorations button, then search and install Ghost decoration.



Cursor Theme:


Click on the Cursor Theme tab and then the Get New Theme button. Search and install Tronnix.




Desktop Theme :


In the Desktop Theme tab, click the Get New Themes button and install the Ghost theme. 



Application Color :


Go to System Settings → Application Appearance and click on the Colors tab. Install the Ghost Color Scheme.



In the GTK option, you can select any dark theme. I have installed MediterraneanNightDarkest for GTK2 and Ambiance-Graphite for GTK3. That's completely your choice, and I would always look forward to better choices from readers :)

Icon Theme:


In the Icons tab from System Settings → Application Appearance, click on Get New Themes button and install DarkFuture theme.



Thus, you are done!

Now you need to take care about your few icons. For your Konsole profile, see the screenshot :


Also, change the Kickoff Launcher icon:



For the final tweak, remember you can't easily change the wallpaper of your Screen Locker. Qiana KDE will always display you the Elarun wallpaper when you lock your screen. This looks really weird, as the Horus wallpaper looks far better. For this, simply make a backup of the Elarun wallpaper and replace Elarun with Horus. I hope this screenshot will demonstrate it :


Now when you lock up the screen, you get your usual Horus wallpaper:


Thus here is my Desktop after making all the configurations :



I hope you liked the looks of my desktop. Well, I am looking forward to improvements and suggestions, so don't forget to place your valuable comments below....Happy theming!


Sunday, 9 November 2014

To Do's After a Fresh Linux OS Installation

Hey there, as I mentioned in the last post, I had to quit OpenSUSE due to overheating. So I went for a short distro hunt in the Linux world.

Well the first option that came in my mind was obviously Ubuntu, my first distro when I entered the Linux world 2 years ago. Ubuntu has a nice interface and Unity is a pleasing eye-candy. Though many still criticize Unity, I am its good fan.
But I needed my KDE back! And sorry Gnome fans, Brasero, Rhythmbox, Shotwell and other Gnome apps are no match for the powerful K3b, Amarok, DigiKam and similar KDE apps.

And yes of course, Kubuntu was a big NO for me. The reason is, Kubuntu and other *ubuntus being derivatives of Ubuntu, never receive the proper attention from the developers.

So the other option that came in my mind was Linux Mint. Linux Mint is well known for its stability, reliability and beauty and elegance. Some call it Linux for beginners, but I would call it a wise distro as most of the things work out of the box, without much post-install configurations. 
And the best thing, Linux Mint has a KDE version too!



So I tried the live session of Linux Mint KDE 17 (Qiana). It worked like charm, no such overheating and far stable than Kubuntu, not to mention that Qiana is LTS, so it will be supported till 2019.

I am penning down some of its features worth noticing:
  • Preinstalled codecs : Play mp3, mp4, flv files, watch videos in YouTube, just after installing your OS. It works great, install it, and start working.
  • Synaptic Package Manager : Qiana KDE has Synaptic as its default package manager, unlike Kubuntu, which has the buggy Muon Package Manager.
  • Stability : KDE being the heaviest DE, demands stability which Qiana provides well.
  • Preinstalled Software : Most of the important software like Gimp, DigiKam , Ksnapshot, LibreOffice suite, Vlc media player, USB Image writer are already installed.
  • Dolphin : The default KDE file manager, Dolphin, is one of the most feature rich file manager I have ever seen for any OS. Linux Mint KDE adds little more beauty to it by the beautiful icon set and makes the "boring" default folder icons better. Just have a look :


So finally I installed Qiana KDE. Installing a fresh Linux distro calls for a complete list of software and tweaks needed by the newbies. I am making a note of such software required to make Linux feel you right at home. The following list is helpful for Ubuntu users also:

  • Update the system: To do this, enter the commands sudo apt-get update; sudo apt-get upgrade in the terminal. In Ubuntu, synaptic package manager is not installed by default, so to install it, enter the following in the terminal: sudo apt-get install synaptic
  • Pictures:
    • Picture viewer: Gwenview is already installed for viewing pictures. Ubuntu also has the picture viewer preinstalled.
    • Editor: Gimp is preinstalled in Qiana, but not in Ubuntu. Also it is better to install extra packages for Gimp in both distros, so make sure you have the following packages installed by opening synaptic package manager:
      • gimp
      • gimp-data
      • gimp-plugin-registry
      • gimp-data-extras
    • For managing your digital picture collections, DigiKam is preinstalled, and Ubuntu also has Shotwell preinstalled.
    • Drawing vector and simple graphics : Install Inkscape. Search inkscape in synaptic and install it.
  • Videos:
    • Media Player : Vlc is preinstalled, Ubuntu users need to install Vlc, so search vlc in synaptic. Personally I prefer SMPlayer to Vlc. Search smplayer in synaptic and install it. It is always good to have more than one player after all!
    • Video Editor: No match for the Kdenlive, install it from synaptic. Ubuntu users may also try Openshot instead, if they don't want to bloat their system with KDE libraries.
    • Sound editor: Audacity is what you need in this case, and it can be installed easily from synaptic by searching audacity.
    • Music Player: Amarok is preinstalled, and Ubuntu also has its Rhythmbox.
    • Audio Tagger: I like to keep my music collection well maintained, and use a tagger to manage the audio tags. For this I use EasyTag. Install it from synaptic by searching easytag.
    • Webcam: Though I am a big an of KDE, I must admit that Cheese still rules. The KDE users may install Kamera and Kamoso apart from Cheese to make their collection more flexible. Install them by searching cheese, kamera and kamoso
    • 3-D Modelling: Blender, install it from synaptic by searching blender
  • Internet:
    • Web Browser: Firefox is preinstalled in both Qiana and Ubuntu. But you can install Google Chrome and Opera as well. They are not available from the default repositories and thus can't be installed by synaptic. Hence you need to download the respective .deb files (similar to .exe files in Windows OS). To install any .deb package, I would always recommend you to do it from terminal. This ensures that you get a debug output as well in case the installation fails due to any error or unmet dependencies. To install a .deb package, open the terminal, go to the respective directory and enter:
      sudo dpkg -i <package-name>
      dpkg is the Debian Package Manager, -i option is for installation.
    • Mail Client: Qiana KDE has KMail already installed, but it is better to make sure that Kontact is also installed. Search kontact in synaptic. Ubuntu users can install the all time favourite Mozilla Thunderbird from synaptic by searching thunderbird.
    • IRC Client : Konversation is already installed in Qiana, and Ubuntu users can install X-Chat from synaptic, the package name is xchat
    • Messaging Clients : Kontact ( KDE IM ) is already installed, Ubuntu users can install Pidgin by searching pidgin from synaptic.
    • Torrent Client : Qiana KDE has KTorrent installed while Ubuntu has Transmission installed. Transmission is a very light weight client, so to get a more feature rich client I would recommend Deluge. Install it by searching deluge in synaptic.
    • Miscellaneous : Apart from these, Skype, Teamviewer, Google Earth (A similar software, Marble, is available in the repositories) and other software can be installed from their respective websites. The .deb packages are readily available.
  • Development:
    • Office Suite: Though LibreOffice is now much more improved, you can install Apache Open Office if you prefer. Don't forget to remove LibreOffice to avoid collisions. Apache Open Office can be downloaded from their website. Once you download the archive file, you will need to extract it. You will get a directory full of .deb packages. When there are more than one packages to be installed, installing them one by one is not recommended as each package depends on the other. So in the terminal, go to the package directory and enter the following:
      sudo dpkg -i *.deb
      The Debian Package Manager resolves the dependencies and installs all the packages.
    • Text Editor: KDE's text editor, Kate, meets all the needs for a programmer's text editor. For Ubuntu, I find gedit a bit novice in front of Kate, and hence would recommend you to install Sublime Text . It can be downloaded from their website. Other than that, for the CLI, make sure you have vim and nano installed from synaptic.
    • Make sure you have gcc ( already installed ) and g++ for C and C++ developing.
    • Oracle Java 8 : Qiana may have preinstalled OpenJDK/JRE, but I would recommend to install Oracle Java instead. Type in the following in the terminal :
      • sudo add-apt-repository -y ppa:webupd8team/java
      • sudo apt-get update
      • sudo apt-get install oracle-java8-installer
      Now make sure to remove the OpenJDK/JRE from synaptic to avoid collisions. To do this, search openjdk in synaptic and remove them if installed.
    • If you are a python developer, install idle-python3.4,  ipython3 from synaptic.
    • For IDEs, install Netbeans and Eclipse from their websites. Netbeans can also be installed from synaptic, search netbeans.Netbeans already installs the Glassfish server for you, so no need to install Apache Tomcat Server.  For html editing, there is no match for Bluefish, install it by searching bluefish from synaptic.
    • For DBMS, I would recommend you to install ORACLE MySql (mysql-client, mysql server), which is very much similar to ORACLE DBMS. Install mysql-workbench for the GUI front-end. To install the MySql JDBC driver, search and install libmysql-java from synaptic. 
    • If you work with Microprocessor 8085, GNUSim8085 (gnusim8085) is right for you.
  • Games: SuperTux (supertux-stable), SuperTuxKart (supertuxkart), (K)Mines, Sudoku, 0ad and many games can be installed. Linux also supports Steam for the dedicated gamers. Don't forget to install SuperTuxKart, you wont regret.
  • Utilities:
    • Many utility software like PDF reader, Archive tool etc. are already installed in the popular Linux distros. For the codecs in Ubuntu, install ubuntu-restricted-extras, libcodec-extra, libdvdread4 (after installing this package, run the following from terminal : sudo /usr/share/doc/libdvdread4/install-css.sh) ,  and for the archiving extras, install rar and unrar
    • Preview for pdf files in dolphin(KDE) can be enabled by installing the package kdegraphics-thumbnailers 
    • Wine (wine, q4wine[for KDE], winetricks, wine<version>-amd64, winegecko<versionname>)
    • PlayonLinux (playonlinux)
    • Oracle Virtual Box (virtualbox-nonfree)/ VMWare Player (Downloadable from their website)
    • Artha offline dictionary (artha)
    • Yakuake (yakuake), a beautiful and handy drop-down terminal.
    • Dosbox (dosbox) for running old DOS programs and DOS games.
    • Partition Manager : The KDE partition manager is preinstalled in Qiana KDE, but for Ubuntu, you will need to install gparted from synaptic.
    • CD burner : I would recommend installing K3b for both Ubuntu and Qiana. K3b is far better than Brasero, the default CD burner for Ubuntu. Install the package k3b from synaptic.
    • Boot-Up Manager : For both Qiana and Ubuntu, install it to control the startup services and programs easily ( though you must be cautious enough else you may mess up with your system ). Install the package bum from synaptic.
    • Duplicate File Searcher: You can install FSLint (fslint) and fdupes to search and remove duplicate files. 
    • Preload : preload can be installed to make your system boot faster. Install the package and run sudo preload in the terminal to start it. To manage it use the Boot Up Manager.
    • Misc: Don't forget to install youtube-dl, the CLI utility to download videos from YouTube and similar websites efficiently.Acetone ISO (acetoneiso) can also be installed to manage CD/DVD images, though Ubuntu itself manages them beautifully. For the Ubuntu users, I would recommend installing the Unity Tweak Tool (unity-tweak-tool), then Variety, the wallpaper sequencer. To install it, enter the following in the terminal : 
      • sudo add-apt-repository ppa:peterlevi/ppa
      • sudo apt-get update
      • sudo apt-get install variety
So this completes my list for the general software that I needed after a fresh Linux OS install. You can suggest more software to enrich the above list. Please put your valuable suggestions and queries in the comment section below.

Saturday, 1 November 2014

Temporary Switch to OpenSUSE

Hey there...writing another post after a long time. Well a lot of things happened within this interval. Firstly I decided to give OpenSUSE 13.1 a try, and I was pretty well satisfied with the OS, what I can call a complete OS.


The features which I liked in OpenSUSE 13.1 :
  • Rock hard stability: Well I am a big fan of KDE and sadly I must admit that Kubuntu can't manage KDE well. This is where OpenSUSE 13.1 excels. During the installation it asks you to choose the DE, and after choosing KDE, I didn't
    repent. All KDE software were running like charm, without crashing even for once. In Kubuntu I hated when DigiKam, Amarok, the Network Manager system tray icon and other important software crashed frequently.
  • Software: I installed OpenSUSE from its complete installation disc. This DVD image with approx. 4.5 gigs in size, is not meant for live-session. The best thing is you get most of your software preinstalled. After installation, I found that DigiKam, Gimp, and other main software were installed already. So it works out of the box, you just need to install the codecs.
  • LibreOffice: Yes, before trying OpenSUSE, I was not a very big fan of LibreOffice. In Kubuntu (and Ubuntu too), you can never get the spell-check work correctly. Also LibreOffice crashed frequently in Kubuntu. OpenSUSE assures you that you will get complete freedom in LibreOffice. The welcome screen and loading-screen tweaks are eye-candy, and the spell-check works like charm, not to mention the stability, making it never annoy you by crashing again and again.
  • YaST : The central configuration manager for OpenSUSE gives you the option to do everything with your OS. You can install or remove software, change the Desktop appearance, and much more. Take it as the “Control Panel” equivalent (though much more than that!) for Windows.
  • Package Management: Kubuntu's Muon package manager and Muon Discover are terrible. Most of the time I used to miss synaptic package manager, until I finally had to install it. The package manager of OpenSUSE is as good as synaptic, and the “zypper” command line utility for installation or removal of packages is very simple yet powerful.
  • The OpenSUSE community: The community is very helpful and you can get help anytime if you are stuck. It feels like being a part of the OpenSUSE family. Updates are readily available and can be easily downloaded just from the Update system tray. Also check out there channel in YouTube to get tonnes of helpful videos.

Although having countless number of features, I had to revert back, luckily not to Kubuntu, but to Ubuntu, once again, just because of these two reasons:
  • Laptop overheating: This haunted me every time I worked. In Kubuntu 14.04 LTS, this overheating problem doesn't even exist. But in OpenSUSE, I was troubled all the time with my noisy fan and increased temperatures. The average temperature remained at >95°C. I had to install TLP for this, but of no use. TLP hardly reduced some of the noise and lowered the temperature to 90°C. This was the main reason that made me switch back to the Ubuntu family.

  • Software Installation: Frankly speaking, software installation was never a bad point. I admit that being from the .deb family it takes a bit time to get adjusted to the .rpm family. I liked zypper, and I must agree that software installation is much faster in OpenSUSE. But being from the Ubuntu family, I was missing the “sudo apt-get install” line. Also you won't get a “Software Center” in OpenSUSE, but they have the “One Click Install” feature in their website, from where you can install software with a single click.
    Each time you start YaST2 to install a software, it tries to refresh the list first by downloading content. You can always skip this option though.
I must appreciate the stability provided by OpenSUSE, but would recommend OpenSUSE only for desktops, where overheating is not an issue to worry about. I hope they fix this problem soon, but till then, I must say good-bye to OpenSUSE, of course with a heavy heart... :(

In the next post, I will be discussing about a fresh new Ubuntu installation. And, please don't forget to share your views about OpenSUSE in the comment box.


Wednesday, 10 September 2014

String Processing in BASH: Find and Replace


The Linux bash shell has many wonderful string processing techniques which if efficiently exploited, give you enormous power to manage your files. Though many techniques are available, I found the  find-replace technique the most interesting. 

Consider a real-life problem:

I have 50 mp3 files in a directory named “Tracks”. Now I want the blank space in each file name to be replaced by the  “-” symbol [ I want this because if you are working in command-line, typing file names with a blank space in them is rather tedious]. Now I have the GUI approach in which I will have to individually rename each of the 322 files one by one ! [ Oh God! Please take me away before I try this! ]. The other way is the command line, which can do your job in less than 10 seconds depending on your typing speed of course!

I assume that you are a bit familiar with the basics of  bash shell scripting, like the for loop, echo command, variables, wild card * and the $ character.

The basic format is :

${string/find/replace}

where string is the variable containing the string to be searched, find is the pattern to be found and replace is the string to be replaced. This will search the string for the given pattern and replace the first occurrence with the replacement string.
If you want to replace all the occurrences, use a '/’ before your pattern :

${string//find/replace}

Open your terminal and type in the following:

string="HelloWorld”
str=${string/l/+}
str2=${string//l/+}
echo $str
echo $str2

The output is self explanatory.



Now as we are familiar with the command, we can use it for renaming our music files. The basic idea is to use a for loop for the purpose.

IMPORTANT:
Before trying out a newly written script which does file management, it is highly recommended that you backup the directory you want to use your script on, because if your script contains errors, you may mess up with your files., even losing them forever.

Take a look at my files first:



Now here is the simple script:
For those who are not familiar with scripts, enter each line in the terminal, one by one.
First, make sure that you are in the right directory by using the cd command.

for i in *; do
     new=${i// /-}
     mv "$i" "$new"
done

Explanation:
The explanation is rather simple. The for loop uses a variable i for iteration, the iteration working on all files in the directory as we have used the '*' wildcard. In each iteration, i contains the file name. A variable, new, stores the processed new file name, containing the blank spaces replaced by “-”. Finally we rename the file name using the mv command.




Viola! All of my file names have been processed, the way I wanted, and it took me a very little amount of time. Isn't it great ???

There are many more such examples where you will come to know the real power of the command line. I hope this post was interesting for you guys. Don’t forget to comment your queries and suggestions below.

Monday, 25 August 2014

Process in Linux : An Overview



Well, enough of the GUI stuff. Now I think it is the time to move inside Linux. Let us have a little glimpse of the process management done in Linux.
By definition, any instance of a particular program in execution at a time is called a process. So a program, when is being executed, is called a process. The concept of process holds for all modern OS, and hence an understanding of the same helps us understand our OS.



To list the process, we can use the ps command. Type in the following to get a long listing of all processes in the system:

ps -el

The ‘e’ option selects all process, and the ‘l’ option is for long listing mode of display.
Each process has a distinct ID called the process id or ‘pid’. Also, its parent process id is thus referred as ‘ppid’.
To kill a process use the ‘kill’ command with the process id. For example, the following command will end the process with pid 20170:

kill 20170

Don’t you think it is faster than using CTRL+ALT+DEL -> select a process -> end process in Windows ?
Or if you are fond of the GUI side, simply type ‘xkill’ in the terminal. Your cursor will change to a skull. Now you simply need to click on a program window you want to close.  Try it, it is rather fun!


Beware! If you click it on your desktop, your desktop will be gone, and you may have to log out again to bring it back. Though many distributions are intelligent enough to bring the desktop again along with a ‘crash menu’ reporting the unexpected closing of your desktop, without making you log out.

Now let us write a code to create a process. Basically a process is created from another process by using the ‘fork()’ system call. The new process is called the child process.  fork() returns an integer, which may have value:
  • fork() < 0 : This means child process creation failed.
  • fork() = 0 : Child created, executing child process.
  • fork() > 0 : Child created, executing parent process.

System calls to get the pid and ppid are ‘getpid()’ and ‘getppid()’ respectively.
Here is a C code to create a process:

#include <stdio.h>
int main()
{
      printf(“ Current process id: %d\nParent process id: %d”, getpid(), getppid());
      int v=fork();
      if(v<0) printf("Child process creation was not successful!\n");
      else
      {
            if(v==0)
            {
                // code for child process
                printf("Child process started with pid:%d and parent id:%d",getpid(),getppid());
                printf("\nChild prints 1 item\nChild will exit now\n");
            }
          else
           {
              // code for parent process
              printf("Parent process running with pid:%d\n",getpid());
              printf("Parent prints 1 item.");
            }
      }
      printf("Exiting process %d with parent pid: %d\n",getpid(),getppid());
      return 0;
}

Two special categories of process which are worth mentioning are orphan process and zombie process.

Orphan Process:

In the long listing of process, the second column indicates whether the process is sleeping (S) or running (R). If a parent process is killed before its child is killed, the child becomes a ‘orphan process’. In Linux, the very first process is the ‘init’ process. As Linux maintains a tree structure for the processes also, hence an orphan process is a direct violation. Hence, any orphan process is adopted by the init process. Thus there are no orphan process in Linux.
To demonstrate this, let us have a look to this code:

#include <stdio.h>
#include <stdlib.h>
int main()
{
      printf(“ Current process id: %d\nParqent process id: %d”, getpid(), getppid());
      int v=fork();
      if(v<0) printf("Child process creation was not successful!\n");
      else
      {
            if(v==0)
            {
                 // code for child process
                printf("Child process started with pid:%d and parent id:%d",getpid(),getppid());
                printf("\nChild prints 1 item\nChild will sleep now\n");
                sleep(12); //sleep the child for 12 seconds
             }
            else
            {
                // code for parent process
                printf("Parent process running with pid:%d\n",getpid());
                printf("Parent prints 1 item. Parent will be killed now.");
                exit(0); // kill the parent
             }
     }
     return 0;
}

Say you compile it as ‘orphan.out
In the above code, parent gets killed just after creating the child and printing a message on the screen.  Meanwhile the child process sleeps for 12 seconds. In these 12 seconds, simply open up a new terminal and list all the process. Notice the ppid of ‘orphan.out’ is same as that of ‘init’, indicating that now init is the parent of ‘orphan.out’.

Zombie Process:


The name is funny, isn't it? Well it is a good analogy of real world zombies. In ‘Linuxworld’, a zombie is a child process which gets killed before the parent process. The child process, though non existent, is still mentioned in the process register, with a ‘zombie flag’, indicated by ‘Z’ in the second column. The process occupies no resource, except for the pid. Though zombies pose no threat when in less number, they can be very annoying for the system when in large numbers. This is because, Linux has a limited number of pids and it may fall short for pids as they have been already occupied by zombies. Thus no more processes can be started. The process register clears the zombies after a system call, like ‘wait()’ or after the parent is killed. To create a zombie process, you can use this code:

#include <stdio.h>
int main()
{
     printf("Process started...\n");
     printf("process id:%d\tparent process id:%d\n",getpid(),getppid());
     int v=fork();
     if(v<0) printf("Child process creation was not successful!\n");
     else
     {
           if(v==0)
           {
                printf("Child process started with pid:%d and parent id:%d",getpid(),getppid());
                printf("\nChild prints 1 item\nchild will exit now\n");
           }
           else
           {
                printf("Parent process running with pid:%d\n",getpid());
                printf("Parent prints 1 item\nSleeping parent for 20 seconds ");
                sleep(20); //sleep the parent for 20 secs
           }
     }
     printf("Exiting process %d with parent pid: %d\n",getpid(),getppid());
     return 0;
}

Compile this code as ‘zombie.out’. Run the code, and open a new terminal to list the processes.  Notice the ‘Z’ flag in the child process id.

I hope this post helped you get closer to Linux more. Feel free to share your questions and knowledge in the comments below.... till then , happy Linuxing :D !

Sunday, 24 August 2014

Its time to Zip!




Hey guys, sorry for posting so late. I was busy these days due to my semester examination.

Today we are going to discuss about file compression and archiving in Linux. For the Windows users, this may be a bit unconventional. In Windows, you just need to click the compress option in the menu to get a “ZIP Archive” of the selected files and folders. What I mean to say is, Archiving and Compression of files are done altogether. Many Windows users may not even differentiate the difference between compression and archiving. Though the same can be done in Linux by a similar GUI tool, but things done from the command line have their own charm, as I say ;)

Let us make the concepts clear first.

Archiving is concatenation of two or more files into a single file, called the archive file. The total size of this archive file is approximately equal (but not less) to the sum of the files contained in the archive.

On the other hand, Compression is reducing the size of the file on the disk by using certain algorithms. Obviously, if decompression results into the exact file, the algorithm is loss-less, else lossy.
It is a common practice to create an archive of the selected files and then compress it to get the final “compressed archive”. Unlike Windows, in Linux compression and archiving are two different processes. For archiving the most common format is '.tar', which stands for tape-archive.
Once we make the archive, we are ready to compress it using the various compression tools available. The most common tools are gzip, bzip2, zip, 7z, etc. Out of these, 7z has the highest compression ratio but is the slowest. The basic trade-off is between  speed and compression ratio. The most popular tools in Linux are gzip and bzip2. Here we will use the gzip tool, which gives the compressed file extension '.gz'. It is worth mentioning that bzip2 has higher compression ratio than gzip, but is slower than gzip. For general usage, I would always recommend gzip.
The basic strategy is converting the files into an archive, and then compressing it using gzip. Thus a file 'myFile' gets converted into 'myFile.tar' and then into 'myFile.tar.gz'
Luckily, we can do these two things using only one command line tool, 'tar'.
Open the terminal, and select a folder to compress. Say, we select 'directory1' which contains large number of text files.
Now go the parent directory of 'directory1' and enter the following command:

tar -czvf myArchive.tar.gz ./directory1

Note: If we wanted to do the same with files instead of the entire directory, simply enter:

tar -czvf myArchive.tar.gz file1 file2 file3 (...and so on)

Your compressed archive will be created bearing the name 'myArchive.tar.gz' . The .tar.gz extension describes that the directory was first archived into 'myArchive.tar' and then this 'myArhcive.tar' was compressed into myArchive.tar.gz using gzip tool. Alternatively we can give the file name as 'myArchive.tgz'  to show the same. The .tgz or .tar.gz files are also called tarballs.
To extract the file, use the following command:

tar -xvzf myArchive.tar.gz

Now let us explore the tar command in a bit detail:
The basic structure is:
tar <options> <archive name> <file1> <file2> <file3> ....
where the options are:
  • c: Create Archive – Create a “tar” archive
  • z: Zip/ Unzip the archive using gzip ( for bzip2, use “j” )
  • v: Verbose-List the files processed You may exclude this option, but it is a good practice to see what “tar” is doing with your files
  • f: File Archive- Use the archive file. It is a bit complex option, but for now just take it as a good practice to use this option. It asks tar to take the archive to be created for compression.
  • x: Extract archive files from the archive.


The tar tool has numerous such options. For a detailed list, you can view its man page by entering:

man tar

Further, you may first archive the file and then compress it manually using gzip command line tool. For this first create a tar (do not use the “z” option). Now use the gzip tool to compress the tar file. If you want to decompress a .gz file, use the 'gunzip' tool. See the man page of gzip for more details.
Compressed archives are a very good way to backup or efficiently store files which are not required at present. Being a coder, I frequently archive my programs to free up disk space. For simple documents, the compression ratio may be as high as 90% . For example, my folder containing C and  C++ codes with a total size of 106 MB approx, was reduced to 4.43 MB after converting it into a tarball.
But before this news starts making you excited enough to set up your hands at tar, let me give you an important tip:
Do not try to compress multimedia files (Pictures, Videos, Music) as your work will go in vain. This is because most of the multimedia files are already compressed, so you will get very poor compression. PDFs also do not get compressed much, but they can be compressed if you want to free up some MBs. Once I tried to compress 14 movies with a total size of 20 GBs. The entire process took 30 minutes and as a result I got a tarball of 19 GBs. So it was a big waste of my 30 minutes. With 7z, it  took obviously much more time and I had to kill the process in between as I was getting bored ( :D ).