Thursday, October 18, 2012

Install Google Apps using ADB for LG P690B

First it needs to be root, this is the case for LG P690B when enabled debug and connected to PC via USB.
 C:\Users\tv\Downloads\SuperOneClickv2.2\ADB>adb shell
$
$ means unroot (just like sudo on linux root)

Do root follow this link for instruction it takes about few minutes
http://forum.xda-developers.com/showthread.php?t=1443115

After doing the prompt will change from '$' to "#' (root as linux world)
C:\Users\tv\Downloads\SuperOneClickv2.2\ADB>adb shell
# ls  
 # means rooted

Install apps without login to google account, if you follow the above link for root then you already have
ADB installed in your computer. In my case it locates in Downloads directory below.
C:\Users\tv\Downloads\SuperOneClickv2.2\ADB>adb install c:\users\tv\Downloads\Ti
tanium_Backup_root_5_6_0.apk
2335 KB/s (5768864 bytes in 2.412s)
        pkg: /data/local/tmp/Titanium_Backup_root_5_6_0.apk
Success
Titanium_Backup_root is installed without using Google Market which required Gmail account.
More info. http://androidcommunity.com/forums/f4/how-to-install-apps-using-adb-4482/ 

Without connecting to Google account the Wifi signal is Grey or White indicates that it is not sync to Google account because it is installed Google Apps using ADB. The following picture indicates that Wifi is white color it was capture using aScreenShoot apps. Beside the color everything is working surf the web and so on....
With this in mind we can have Android phone runs all the apps without Google knowing about the phone the minute that you login into the Google account you can not logout and the phone is tracked the only thing gets out the Google account by doing the manufacture reset. I try clear data of Google apps or Account sync and none of them seems working. Manufacture reset will wipe out all the data and possible unroot the phone again.
This is becoming important when people gives the phone away. Google should make easy for people to change account or remove account.

Thursday, September 27, 2012

Upgrade tablets Herotab C8 and Novo 7 Advanced to Android 4.0.3

Please make sure back up your data because it will wipe out your data. You can use back up or restore or external tools: I am using Titanium. After finished upgrade just need to restore, it will save a lot of time instead of trying to remember which apps to install again. It is your own risk to do the upgrade, I have no responsible whatsoever regarding this upgrade.

Herotab C8: 

ROM F/W http://www.slatedroid.com/topic/37733-rom-updated-0809-ice-fusion-v02/ Instruction: http://www.slatedroid.com/topic/38255-rom-updated-0809-jol-cm10-alpha2/
1. Extract the zip file to the external SD, or copying files, root.tgz, zImage, recovery, utscript ...... to external SD.
2. Press power + menu to boot midRecovery. JellyBean need a larger system partition, if you are upgrading from another Rom necessary. repartition the internal SD, for this go to step
3, if you already have the correct partitions at step 4. 3. Go to Advanced, "Partition SD card", size of cache 256, size of data 1024, size of system 512. When partitioning the SD erase all data and cache, no need to step
4. go to step 5. 4. For maximum compatibility and that installation is clean with no trace of other Rom, is necessary, "Wipe data \ factory reset" and "wipe cache".
5. Now it's time to install the Rom, go to "Flash ROM", select "(Select this directory)".
6. If the ROM does not include Google applications, you need your installation. Go to "Apply patch \ update" and select the zip file. This step also applies to patch, just zip files, provided for our tablet.
7. If a new kernel can update it. Go to "Partitions and Storage" and "kernel update", select the file zImage.
8. Optionally you can flash the boot logo, Go to "Partitions and Storage" and "Update Logo", select the file logo.bmp.

Ainol Novo 7 Advanced

ROM F/W: http://www.flashmyandroid.com/forum/showthread.php?379-ROM-Ainol-Novo-7-Advanced-Official-ICS-Firmware-v4-0-3v1-0
or http://www.bergfiles.com/i/bf535ed4e1h32i0
Please note this ROM is from manufacture, it is rooted(good thing) and its default language is Chinese after finished upgraded you need to change the languages & input to your language i.e. for my case I change to English but you can guess where is language & input menu from the above picture. It is number 6th from the bottom up.
09/17/2012  07:15 PM    <DIR>          ..
03/08/2012  04:11 PM       331,604,992 Novo7Advanced_0308.img
Imstruction: http://gadgetfreakz.co.uk/downloads/gfz-novo7/Ainol_Novo_7_Firmware_Update_Guide.pdf

You need LiveSuit to connect device to PC to upgrade. Details as follows:


Ainol Novo 7 Advanced Official ICS Firmware v4.0.3v1.0
Download Link: will update soon
Original download: http://115.com/file/bedviw81
Original post: http://bbs.imp3.net/thread-10621519-1-1.html

Installation:
LiveSuit V1.07 http://www.mediafire.com/?idmeiyvr8xbt6rd
Ainol_usb_driver http://www.mediafire.com/?oo4fo44mbkpbz4i
Open LiveSuit then follow instructions.

- After upgraded you may experience with wifi problem, you may see
Under WIFI it says " obtaining IP address from WIFI NAME" then "scanning" then "connecting" then "disconnected." this cycles over and over.
http://androidforums.com/le-pan-tc-970/469573-obtaining-ip-address.html
It is easy to fix there is no thing wrong with the upgrade for some reasons it does not work with WEP security mode in 4.0.3 it prefers WPA or WPA2 Personal. Probably WEP is the least secure enscript.
In my case I just need to login into my router and change from WEP to WPA2, WPA Algorithm to TKIP, WPA Shared Key and pick up a password. For all the wifi devices need to disconnect and connect again for them to work with the new setup if you keep the same password then all you have to do is disconnected/connected. That's all.


- After upgraded if you experience some strange problems like the tablet is reset itself, please go to setting and do Factory/data reset it will stable again need to back up your data first. I was so disappointed after the upgrade and it kept reset itself, to wipe out erase all the data of the tablet and it did the treat.

- If you run into the problem with linux you need to remove network-manager and install wicd, it works for your linux wifi. See http://ubuntuforums.org/showthread.php?t=1560502
Re: Wicd + WPA = Connection Failed, Bad Password?

That fix didn't work for me.

What worked for me was uninstalling network-manager and network-manager-gnome and then rebooting.

I have all above problems. I posted here to share it may save you a lot of time. Sometimes we forget how to upgrade if it was done last year so this post will help for anyone owns a tablet Herotab C8 or Novo 7 Advanced, both of them are ok to use. Herotab C8 has problem with wifi I basically sit in the same room for it to work but it has its own reset button make the upgrade easy but it only has one camera at the front but it is heavy but a solid tablet. Novo7 has both front and back camera but it is not solid as Herotab. Both of tablets have a problem with the battery, they won't last long. They are good for experience since they are so cheap and Android, I am using them to lean and develop Android it is the same that we learn Linux before.

There is no much different from 2.3 to 4.0.3 basically the same except the layout and more stable just a bit/less CPU resource just a bit. I am disappointed on Google for this ICS 4.0.3  release. They should implement something brand new like peek/hub/flow concept of Blackberry 10. I have my phone 2.3 and will keep as it is. Most people thinks that Android is always having the problem because the apps are running Java. I agree Java is slow because it is interpret languages through JVM....so maybe no need to upgrade I see no different from ver. 2.3 to 4.0.3 except some cool layouts. 

 

Wednesday, September 26, 2012

Document with Scribd is better Google docs

If you are the user want to read a document from this blog and if it is stored in google docs you can link with the document but the user needs to login to read the document. With Scribd you don't need it displays as it is. For example my test code doc. Just need go to HTML instead of compose and paste the Embed code into the blog like add youtube video. At Scribd select HTML for embed. To display tablet or Smartphone needs flash and it comes on the old version of Dolphin < 8.5, the new version will no longer support flash.
http://forum.xda-developers.com/showthread.php?t=1787595
Test Code Result

My New System

I can do more things and faster with my new system it is i7
Acer Aspire Desktop Computer featuring Intel Core i7-2600 Processor (AM3970-EB12P)
I know ACER is not that good but it is on sale for $649.00. At work I am using the same system i7 with 32 GB of RAM and I fall in love with the machine this is the reason I bought this machine. At work the linux kernel compile time for the target is reducing from 2 hours to 30 minutes. This system is only 8 GB of RAM can be upgraded to 16 GB. I will even do it later ideally 16 GB is the best but wait to make some money first. I can run 2 VMware and VirtualBox and Photoshop...it is great machine except it is ACER hope that it will last for 2 years, my last ACER monitor was only last for 2 years and died.
  

It came with 1.5 T so I am using 600 for C drive using win 7 with VMware. I was using VirtualBox and start using VMware for the new project which I find VMware is better performance than Virtualbox but Virtualbox offers many tools to convert or clone hard drive. The new system I am using VMware and my old system is using Virtualbox. No need for dualboot machine everything runs from Win 7 as Host since win 7 is much stable now. All linux systems run as Guest. It makes like more easy now with the fast system I just bought. For some reasons I have a Quad AMD 2.4 GHz it runs slow like hell compare to this system i7 this is other reason I bought this system. I built my old system last year for about $350, it is no good to build it is much better to buy the system when it is on sale. To build the system sometimes end up costs more than buy the system when it is on sale.
The new system goes well with 24" inches SamSung S24B350H Monitor for $199, 1/2 of the screen is using for windows and 1/2 of screen is using for linux. With the set of wireless keyboard and mouse from Logitech I am using EX100 wireless keyboard + mouse.  The ACER's keyboard comes with the system is sucked it is small like laptop keyboard, cannot use for the real work. From the net people tells the same thing. This machine also has a lot of USB ports from and back and Multi-in-1 Card Reader which makes so easy to take pictures and upload into the blog.

http://www.bestbuy.ca/en-CA/product/acer-acer-aspire-desktop-computer-featuring-intel-core-i7-2600-processor-am3970-eb12p-am3970-eb12p/10190543.aspx?path=153d5544e3b964502ef2ad79b07960dden02

http://www.samsung.com/sg/consumer/pc-peripherals-printer/monitor/led-monitor/LS24B350HS/XS

http://flexequinox.blogspot.ca/2012/09/how-to-bridge-networking-in-vmware.html

http://flexequinox.blogspot.ca/2012/09/how-to-bridge-networking-in-vmware.html

GParted to resize your existing hard drive

I am using VMware as my Virtual Disk but it is the same as standalone or dualboot machines.
First you need to ISO image I am using linuxmint-13-cinnamon-dvd-64bit.iso which can be downloaded from Linux Mint. You cannot resize the hard driver unless you load from LiveCD or ISO image. i.e.
kubuntu-14.04-desktop-amd64.iso. VMware setting and expand the hard drive you want it.

You need to hit F2 to go to BIOS setup and setup CD as 1st boot. In VMware there are 2 variables on VMX file locates in your Virtual Machines -> Name of  your Virtual Machine.VMX.
If these variables are exist you can add as follow to let VMware knows. The string name are exactly as you see.
bios.bootDelay = "5000"
bios.forceSetupOnce = "TRUE"
The 1st option delay boot time so you have enough time to hit F2 and 2nd option it boots into BIOS or ESC to choose the device to boot up. This is one time boot selection.

This is BIOS of VMware and not BIOS of the system. VMware creates a BIOS similar to BIOS system to handle Boot and other things. VMware using PhoenixBIOS. My system BIOS is ACER.
To distinguish between 2 BIOS. I call system BIOS and VMware BIOS.
When load into this VMware BIOS you need to change CD/DVD file points to ISO that you want to run.
With the virtual machine powered off, open the Configuration Editor (choose Settings then Configuration Editor), and select the DVD/CD-ROM. If not, it won't boot from this iso even you hit ESC to choose CD/DVD boot. This is a virtual CD/DVD drive not physical CD drive !!!. no need to put CD in the physical drive if choose ISO option instead of physical drive. The default of ISO image is pointing to C:/Program Files(X86)/VMware Player/linux.iso all you need to point this to right ISO.
Using edit VMware Hardware then Click on ISO image instead of physical CD/DVD. My case is  linuxmint-13-cinnamon-dvd-64bit.iso the iso just downloaded into Downloads directory.
In this CD/DVD setup choose use ISO to boot and device status select connect at power on so it can boot.
 Remember the new size is only good to VMware but Linux-Mint won't know until you change the size using GParted. YOU CANNOT RESIZE IF IT BOOTS FROM THE SAME HARD DRIVE for example /dev/sda1 if you drive to resize it will prompt that device is busy it needs to umount first and this is the reason we boot from LiveCS ISO image. After it boots we can go change the hard drive of /dev/sda1 because it is umounted.
When ISO boot up choose demo and run from there. Do not select installation all we want is to use Gparted.
If GParted in not installed in this live CD need to install: sudo apt-get install gparted. The ISO is stored from disk or USB, the demo runs from RAM so gparted in run from RAM when it is shut down gparted is gone and it does not write into ISO file. Since the disk expand is rarely using so to issue the command sudo apt-get install gparted is a small thing.

Ref.
http://communities.vmware.com/message/1061677 
http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=102



This is system BIOS. It is different with VMware BIOS above.
If you have a problem to install Win 7 with RAID then Disable RAID in BIOS and enabled native IDE.
RAID (redundant array of independent disks)




Clone VDI or Convert VDI (Virtualbox) to VMDK (VMware)

CLONE VDI
This is the case you want to move VDI to the other machine, Create VM and using existing VDI

C:\Program Files\Oracle\VirtualBox>VBoxManage.exe clonevdi "C:\Users\HP\VirtualB
ox VMs\ubuntu1\ubuntu1.vdi" D:\ubuntu1_test.vdi
0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
Clone hard disk created in format 'VDI'. UUID: 9199a774-2d26-4a60-b186-63eb2d212
831

CONVERT VDI ->VMDSK
This is when you want to move from Virtual disk from VirtualBox to VMware because the new UUID in the VMware setup create the VMware and choose later option. Then delete the Hard drive and create a new Hard driver with the existing VMDK just converted and select option keep existing format. This way the new UUID of VMDK is created in VMX file. See Ref. 3


1. http://www.leonardoborda.com/blog/easily-convert-vdi-to-vmdk-images/
2. http://www.irongeek.com/i.php?page=videos/vmwareplayerlivecd
3. http://www.aztcs.org/meeting_notes/winhardsig/virtualmachines/vmware/Using_VMDK_File_to_Create_a_VM_in_VMwarePlayer--Windows.pdf

c:\Program Files\Oracle\VirtualBox>VBoxManage.exe clonehd J:\ubuntu1_test.vdi J:
\ubuntu1_test.vmdk --format vmdk
0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
Clone hard disk created in format 'vmdk'. UUID: fd4474c9-199f-4a9e-880a-b312ff175e35

c:\Program Files\Oracle\VirtualBox>VBoxManage.exe showhdinfo "j:\ubuntu1_test.vdi"
UUID:                 9199a774-2d26-4a60-b186-63eb2d212831
Accessible:           yes
Logical size:         42756 MBytes
Current size on disk: 34306 MBytes
Type:                 normal (base)
Storage format:       VDI
Format variant:       dynamic default
Location:             j:\ubuntu1_test.vdi

c:\Program Files\Oracle\VirtualBox>VBoxManage.exe showhdinfo "j:\ubuntu1_test.vmdk"
UUID:                 fd4474c9-199f-4a9e-880a-b312ff175e35
Accessible:           yes
Logical size:         42756 MBytes
Current size on disk: 32899 MBytes
Type:                 normal (base)
Storage format:       vmdk
Format variant:       dynamic default
Location:             J:\ubuntu1_test.vmdk


Problem: If you are running into GRUB rescue> 

Then either the VMDK just converted is corrupted or UUID does not match with the new VMDK created.
If there is an error Syntax error line 1 of VMDK probably something to do with the setup as well.
In the VMX there are 
ide1:0.fileName = "\ubuntu1_test.vmdk"
uuid.location = " make sure it matches with uuid of ubuntu1_test.vmdk"
uuid.bios = "
make sure it matches with uuid of ubuntu1_test.vmdk"
make sure they are matching you can use VBoxManage.exe showhdinfo to get UUID.

VirtualBox vs. VMware
VMware performs better Virtualbox. VMware takes less CPU resources than VirtualBox however, for tools as mentioned above, VirtualBox offers more flexible than VMware. I am currently using both VirtualBox and VMware and because it is faster I feel comfortable to use VMware for my future development my trend toward VMware. I have been using VirtualBox everyday for the past 3 years when switch to VMware you definitely see the difference in the performance right away. It is very easy to setup: I have 2 identical virtual disks kubuntu_64.vdi and kubuntu_64.vmdk (using VBoxManage.exe to clonehd) with VirtualBox is running the CPU usage is 50% and with VMware is running the CPU usage is currently 20%. Same hardware and same win 7 is the host. This is how I test. I don't know but this is what I see on my 2 systems: I7@3.4 GHz with 8 GB of RAM and AMD Quad@2.4 GHz with 6 GB of RAM. When it takes less CPU resources you can do more work because you don't have to wait. In order to run VM CPU needs to have VT supported at least Dual Core. 
Even the size of Virtual disk, VMware takes less space for the same image, the difference is 2 GB.
Below is some vdi have been converted to vmdk
09/28/2012  09:59 PM    36,121,522,176 ubuntu1_test.vdi (VirtualBox)
09/28/2012  09:54 PM    34,666,905,600 ubuntu1_test.vmdk (VMware) 


09/27/2012  08:48 PM    30,775,869,952 Kubuntu-64bit.vdi (VirtualBox)
09/27/2012  10:31 PM    28,886,237,184 Kubuntu-64-bit.vmdk (VMware)
continue 

 

Tuesday, September 25, 2012

Thursday, July 19, 2012

linux Kernel 2.6.38 using sema_init

I just found out when upgraded rt73 device drivers that the old Linux kernel and the new version they changed the mutex to semaphore with extra parameter (A mutex is essentially the same thing as a binary semaphore(1 or 0 single resource) vs. counting values that allows multiple program threads to share the same resource)  I could not even grep for the name because the name is totally different. The name is now all low cases sema_init. So the device driver could fail after upgrade to a new Linux kernel and this is the case we need to change the device driver rt73 module rtmp_init.c as follow.
#ifndef init_MUTEX_LOCKED

        sema_init(&(pAd->usbdev_semaphore), 1);            // linux kernel 2.6.38

        sema_init(&(pAd->mlme_semaphore), 1);

        sema_init(&(pAd->RTUSBCmd_semaphore), 1);

#else
        init_MUTEX_LOCKED(&(pAd->usbdev_semaphore)); // linux kernel 2.6.37

        init_MUTEX_LOCKED(&(pAd->mlme_semaphore));

        init_MUTEX_LOCKED(&(pAd->RTUSBCmd_semaphore));  


#endif
//Note:

//currently typically to 1 (in which case the semaphore is called a mutex) 
//From Linus Torvalds
/* Maximum concurrent users 
#define MAX_CONCURRENT_USERS 20
sema_init(&sem, MAX_CONCURRENT_USERS);

However, almost all practical use of semaphores is a special case where
the counter is initialized to 1, and where they are used as simple
mutual exclusion with only one user allowed in the critical region.
Such a semaphore is often called a "mutex" semaphore for MUTual
EXclusion.
*/

Friday, July 13, 2012

LinkedList

In C++
/*
 * part1.h
 *
 */

#ifndef PART1_H_
#define PART1_H_

#pragma once

//---------------------------------------------------------------------------
struct CarPart
{
 long     PartNumber;
 char     PartName[40];
 double   UnitPrice;
 CarPart* Next;

};

//---------------------------------------------------------------------------
class ListOfParts
{
 int size;

public:
 ListOfParts();
 int Count();
 CarPart* Head;

 int Add(CarPart* Item);
 CarPart *Retrieve(int pos);
 bool Delete();
};

#endif /* PART1_H_ */

#include <iostream>
#include "parts1.h"
using namespace std;         //otherwise std::cout


//---------------------------------------------------------------------------
ListOfParts::ListOfParts()  //constructor
// : size(0), Head(NULL)
{
 size = 0;
 Head = NULL;  // either way : size(0), Head(BULL)
}
//---------------------------------------------------------------------------
int ListOfParts::Count()
{
 return size;
}
//---------------------------------------------------------------------------

int ListOfParts::Add(CarPart *NewItem)
{
 CarPart *Node = new CarPart;  //add struct CarPart into the class

 Node          = NewItem;
 Node->Next    = Head;   //of the struct pointer Next
 Head          = Node;   // of class pointer Head
 return size++;
}
//---------------------------------------------------------------------------
CarPart *ListOfParts::Retrieve(int Position)
{
 CarPart *Current = Head;
 for(int i = 0; i < Position && Current != NULL; i++)
 {
  Current = Current->Next;
 }
 return Current;
}
//---------------------------------------------------------------------------
bool ListOfParts::Delete()
{
 if( Head == NULL )
 {
  cout << "The list is empty\n";
  return false;
 }
 else
 {
  CarPart *Current;

  Current = Head->Next;
  Head->Next = Current->Next;
  size--;
  return true;
 }
}

#include <iostream>
#include <string.h>
#include <stdio.h>

#include "parts1.h"


using namespace std;

//---------------------------------------------------------------------------
int main()
{
 ListOfParts *Parts = new ListOfParts();     //class
 CarPart     *Part;       //struct

 // Visual C++ 6 can't "scope" a variable in a for loop
 int i;

 Part  = new CarPart;
 Part->PartNumber = 9743;
 strcpy(Part->PartName, "Air Filter");
 Part->UnitPrice  = 8.75;
 Parts->Add(Part);

 Part  = new CarPart;
 Part->PartNumber = 27487;
 strcpy(Part->PartName, "Clutch Disk");
 Part->UnitPrice  = 47.15;
 Parts->Add(Part);

 Part  = new CarPart;
 Part->PartNumber = 87873;
 strcpy(Part->PartName, "Brake Disk");
 Part->UnitPrice  = 35.15;
 Parts->Add(Part);

 Part  = new CarPart;
 Part->PartNumber = 27644;
 strcpy(Part->PartName, "A/C Filter Drier");
 Part->UnitPrice  = 55.55;
 Parts->Add(Part);

 cout << "Number of Parts: " << Parts->Count() << endl;

 cout << "\n-=- List of Parts -=-";
 for(i = 0; i < Parts->Count(); i++)
 {
  CarPart* One = Parts->Retrieve(i);

  cout << "\nCar Part Information";
  cout << "\nPart #:      " << One->PartNumber;
  cout << "\nDescription: " << One->PartName;
  cout << "\nUnit Price: $" << One->UnitPrice << endl;
 }

 Parts->Delete();

 cout << "\nNumber of Parts: " << Parts->Count() << endl;

 cout << "\n-=- List of Parts -=-";
 for(i = 0; i < Parts->Count(); i++)
 {
  CarPart* One = Parts->Retrieve(i);

  cout << "\nCar Part Information";
  cout << "\nPart #:      " << One->PartNumber;
  cout << "\nDescription: " << One->PartName;
  cout << "\nUnit Price: $" << One->UnitPrice << endl;
 }

 return 0;
}
Output:
Number of Parts: 4

-=- List of Parts -=-
Car Part Information
Part #:      27644
Description: A/C Filter Drier
Unit Price: $55.55

Car Part Information
Part #:      87873
Description: Brake Disk
Unit Price: $35.15

Car Part Information
Part #:      27487
Description: Clutch Disk
Unit Price: $47.15

Car Part Information
Part #:      9743
Description: Air Filter
Unit Price: $8.75

Number of Parts: 3

-=- List of Parts -=-
Car Part Information
Part #:      27644
Description: A/C Filter Drier
Unit Price: $55.55

Car Part Information
Part #:      27487
Description: Clutch Disk
Unit Price: $47.15

Car Part Information
Part #:      9743
Description: Air Filter
Unit Price: $8.75
In Java, it is much simple with a lot of less lines. Java has so many rules but it can be easy when you are master of the rules. I try to output the same format as C++. But it does more for example removeLast/removeFirst/getFirst/getLast item of the list and so on....LinkedList is a part of java.util.* so it is much easy.
//http://www.javatutorialhub.com/java-arrays.html
import java.util.*;

class CarPart{
 long     PartNumber;
 String   PartName;
 double    UnitPrice;
 CarPart(int i, String s, double j){
   PartNumber = i;
   PartName = s;
   UnitPrice = j;
 }
   public String toString() {
        
        System.out.println("Car Part Information");
     return "Part #:  "+ PartNumber + "\n" +"Description: "+ PartName + "\n" + "Unit Price " + UnitPrice;
    }
 
}

class LinkedListPart{
   public static void main(String args[]){
     LinkedList<CarPart> parts = new LinkedList<CarPart>();
     parts.add(new CarPart(9743,"Air Filter",8.75));
     parts.add(new CarPart(27487,"Clutch Disk",47.15));
     parts.add(new CarPart(87873,"Brake Disk",35.15));
     parts.add(new CarPart(27644,"A/C Filter Drier",55.55));
     System.out.println("Number of Parts " + parts.size());
     for (CarPart element : parts) 
       System.out.println(element + "\n");
     parts.remove(0); 
     System.out.println("--After remove first part from LinkedList---"); 
     for (CarPart element : parts) 
       System.out.println(element + "\n");
     parts.removeLast();
     System.out.println("---After remove last part from LinkedList---"); 
      for (CarPart element : parts) 
       System.out.println(element + "\n");
  }
}

Output:
Number of Parts 4
Car Part Information
Part #:  9743
Description: Air Filter
Unit Price 8.75

Car Part Information
Part #:  27487
Description: Clutch Disk
Unit Price 47.15

Car Part Information
Part #:  87873
Description: Brake Disk
Unit Price 35.15

Car Part Information
Part #:  27644
Description: A/C Filter Drier
Unit Price 55.55

--After remove first part from LinkedList---
Car Part Information
Part #:  27487
Description: Clutch Disk
Unit Price 47.15

Car Part Information
Part #:  87873
Description: Brake Disk
Unit Price 35.15

Car Part Information
Part #:  27644
Description: A/C Filter Drier
Unit Price 55.55

---After remove last part from LinkedList---
Car Part Information
Part #:  27487
Description: Clutch Disk
Unit Price 47.15

Car Part Information
Part #:  87873
Description: Brake Disk
Unit Price 35.15

Tuesday, July 03, 2012

Why default constructor is required(explicitly) in a parent class if it has an argumented constructor

class A {    
  A(int i){    
  }
}
class B extends A {
}
class Main {    
  public static void main(String a[]){
    B b_obj = new B();
  }
}
This will be an error: cannot find symbol constructor in B If we don't have argument constructor the compiler will insert super() the first line in derived class constructor. Since the parent has parameter(arguments) constructor, it supersedes the default constructor in A, the compiler could not find the default constructor per error showing therefore so we need to insert the default constructor.
So class A will have 2 constructors: default A(){} and A(int i){}.
2 ways to fix it
- has a default constructor in parent class A
- has a super(int) in B constructor
class A {    
  A(int i){    
  }

  A(){}     //insert the default constructor in the base class, derived class unchanged 
}
class B extends A {
}
class Main {    
  public static void main(String a[]){
    B b_obj = new B();
  }
}
 

class A {    
  A(int i){    
  } 
}
class B extends A {

  B(int i) {    // add constructor for B with super(i) in the 1st line

  super(i); 

  }
}
class Main {    
  public static void main(String a[]){
    B b_obj = new B(2); //constructor has a value
  }
}
Same thing in C++ you need to create a default constructor for base class if the base class has arguments constructor as long as this argument/parameter constructor is exist the compile will not create default constructor. In Java you can use "super" keyword to call parameter constructor is must be the first line of derived/child constructor. To be compatible for both C++ and Java it is always good to have the parent default constructor.
class A { 
 int i;
  public:  
  A(){}  
  A(int i){}   //A(int i) no default constructor you have to create one above A(){} like Java
};
class B : public A {
  public:
};

int  main(){
   B *b_obj = new B;  // for B compiler will use default constructor B(){} requires A(){}
}
See this for the full behaviors of C++ WRT constructors: http://en.wikipedia.org/wiki/Default_constructor
if you specify a constructor, the compiler will not create a default one for you. The compiler will define a default ctor if and only if you don't explicitly declare any ctors. It is confusing when there is a parent and child class (derived class). In the above examples, we think that the compiler will generate the default constructor for the child class since there is no constructor is defined so it creates a default constructor for the child but when the object is created in the child class, the parent constructor is called first then the child constructor, this is where the error happens because it could not find the default constructor in the parent class.
This rule applies to Java and C++ as well.
Another way to do is let the child class initializes the base class ctor then no default ctor at base class as long as the compiler know there is one ctor is defined so it does not look for a default ctor. This is the case there is no source code for base class just a library to link and it can be set in the derived class (child class)
#include <iostream>
using namespace std;

class A { 
 int i;
  public:  
  //A(){}  
  A(int i){}   //A(int i) no default constructor you have to create one above A(){} like Java
};
class B : public A {
 public:
 int j;
 B():A(j){}   // derived class initialize the base class constructor
};

int  main(){
   B *b_obj = new B;
}

Wednesday, June 27, 2012

Templates

A generic function defines a general set of operations that will be applied to various types of data. For example using template to swap a float, int or char.

Function Template:

// Function template example. p.751 BorlandC
#include <iostream>
using namespace std;
// This is a function template.
//void swapargs(int &a, int &b)
//{
////X temp;
//int temp = a;
//a = b;
//b = temp;
//}
//void swapargs(float &a, float &b)
//{
////X temp;
//int temp = a;
//a = b;
//b = temp;
//}
//void swapargs(char &a, char &b)
//{
////X temp;
//int temp = a;
//a = b;
//b = temp;
//}
template <class X> 
void swapargs(X &a, X &b)
{
X temp;
temp = a;
a = b;
b = temp;
}

int main()
{
int i=10, j=20;
float x=10.1, y=23.3;
char a='x', b='z';
cout << "Original i, j: " << i << ' ' << j << endl;
cout << "Original x, y: " << x << ' ' << y << endl;
cout << "Original a, b: " << a << ' ' << b << endl;
swapargs(i, j); // swap integers
swapargs(x, y); // swap floats
swapargs(a, b); // swap chars
cout << "Swapped i, j: " << i << ' ' << j << endl;
cout << "Swapped x, y: " << x << ' ' << y << endl;
cout << "Swapped a, b: " << a << ' ' << b << endl;
return 0;
}

Output:
Original i, j: 10 20
Original x, y: 10.1 23.3
Original a, b: x z
Swapped i, j: 20 10
Swapped x, y: 23.3 10.1
Swapped a, b: z x

Class Template:

// class templates
#include <iostream>
using namespace std;

template <class T>
class mypair {
    T a, b;
  public:
    mypair (T first, T second)
      {a=first; b=second;}
    T getmax ();
};

template <class T>
T mypair<T>::getmax ()
{
  T retval;
  retval = a>b? a : b;
  return retval;
}

int main () {
  mypair <int> myobject (100, 75);
  cout << myobject.getmax();
  return 0;
}

Saturday, June 16, 2012

Const and Reference

Const, Pointer and Reference in C/C++ Passing by reference or pointer in doubleit resulting the values in main will be altered
//in C no reference using pointers changes the value of memory location resulting altering the values in main
#include <stdio.h>
 
void doubleit( int *x, int *y){
   *x *= 2;
   *y *= 2;
}
 
int main(void){
   int x = 10;
   int y = 5;
   doubleit( &x, &y);
   printf("%i %i",x,y);
   return 0;
}
//C++ using references change the value of memory location resulting altering the values in main
#include <stdio.h>
 
void doubleit( int &x, int &y){
   x *= 2;
   y *= 2;
}
 
int main(void){
   int x = 10;
   int y = 5;
   doubleit( x, y);
   printf("%i %i",x,y);
   return 0;
}
//C/C++ passing by values the values in main will not change, it makes a copy x, y for doubleit and it will be destroyed when function is returned
#include <stdio.h>
 
void doubleit( int x, int y){
   x *= 2;
   y *= 2;
}
 
int main(void){
   int x = 10;
   int y = 5;
   doubleit( x, y);
   printf("%i %i",x,y);
   return 0;
}
//Const, Reference and values
#include <stdio.h>
 
 
//void doubleit(int x, int y){  //unchange the values x, y in main copy varibles and keep the original in main
//void doubleit(int &x, int &y){  //change values x, y in main by reference 
void doubleit(const int &x, const int &y){ // unchange the values x, y in main by const compile will check if it is altered can read only
// which will cause variable to be passed by reference without copying but stop it from being altered.
//x *= 2;
//y *= 2;
 int i = x*2;
 int j = y*2;
 printf("%i %i\n",x,y);
}
 
int main(void){
 int x = 10;
 int y = 5;
  
 doubleit(x,y);
  
 printf("%i %i",x,y);

  
 return 0;
}
Even more useful is a pointer (constant or otherwise) to a ‘const’ value. This is useful for returning constant strings and arrays from functions which, because they are implemented as pointers, the program could otherwise try to alter and crash. Instead of a difficult to track down crash, the attempt to alter unalterable values will be detected during compilation. For example, if a function which returns a fixed ‘Some text’ string is written like char *Function1() { return “Some text”;} then the program could crash if it accidentally tried to alter the value doing Function1()[1]=’a’; whereas the compiler would have spotted the error if the original function had been written const char *Function1() { return "Some text";} because the compiler would then know that the value was unalterable. (Of course, the compiler could theoretically have worked that out anyway but C is not that clever. Passing an object by reference.
// C++
class Type; // defined somewhere before, with the appropriate operations
void swap( Type & a, Type & b ) {  //like variables need & for function
   Type tmp = a;
   a = b;
   b = tmp;
}
int main() {
   Type a, b;
   Type old_a = a, old_b = b;
   swap( a, b );    //like in the previous example for variables just the name
   assert( a == old_b );
   assert( b == old_a ); 
}
The swap function above changes both its arguments through the use of references. The closest code in Java:
//Java
public class C {
   // ...
   public static void swap( C a, C b ) {
      C tmp = a;
      a = b;
      b = tmp;
   }
   public static void main( String args[] ) {
      C a = new C();
      C b = new C();
      C old_a = a;
      C old_b = b;
      swap( a, b ); 
      // a and b remain unchanged a==old_a, and b==old_b
   }
}
The Java version of the code will modify the copies of the references internally, but will not modify the actual objects externally. Java references are C pointers without pointer arithmetic that get passed by value into functions. Can I access private members from outside the class without using friends in C++? Yes, you can Conceptually in C/C++
#include <iostream>
#include <string>
using namespace std;
int main(){
 int i = 2;
 int *j = &i; //j and i are the same in memory location
 *j = 4;  // change value of i because the same memory location for i and j
 cout << i << endl;
return 0;

AccessMemoryOfPrivateUseFriend.cpp: In function ‘Student Show(std::string, int)’:
AccessMemoryOfPrivateUseFriend.cpp:7: error: ‘std::string Student::name’ is private
Therefore we need a friend keyword function like this.
#include <iostream>
#include <string>
using namespace std;

class Student {
     private:
       string name;
       int grade;
     public:
       void ShowStudent() { cout << name << " " << grade << endl;}
       friend Student Show(string, int); //friend function to access class private
 };
Student Show(string s, int y)
{
   Student T;
   T.name = s;
   T.grade = y;
   return T;
}

int main(){
  Student S;
  S = Show("Tom", 10);
  S.ShowStudent();
  return 0;
 }
Output: Tom 10
Without Friend we can do as with the above for integer. 
Create another class with the same layout as the object with private members but with private changed to public. Create a variable of pointer to this class. Use a simple cast to point this to your object with private members and try calling a private function.
#include <iostream>
#include <string>
using namespace std;

class Student {
     private:
     string name;
     int grade;
  public:
     void ShowStudent() { cout << name << " " << grade << endl;}
 };
class Me {
 public: 
  string myname;
  int mygrade;
}; 
int main(){
  Student T;
  Me *p;
  p = (Me*)&T;
  p->myname = "Tom";
  p->mygrade = 10;
  T.ShowStudent();
  return 0;
 }
Output: Tom 10 (we get the same output as friend function before without using friend)
Using template to access private members of the class.
#include <iostream>
using namespace std;
class safe
{
    int money;

public:
    safe() : money(1000000){ cout << "Constructor is called initializes 1000000" << endl;}

    template <typename T> //template
    void backdoor()
    {
     money -= 50000;
     cout << "Template "<< money << endl;
    }
    //void take(){ safe T; T.money -= 1; cout << T.money << endl;}
    friend void take(safe);
};
void take(safe T) { T.money -= 1; cout << "Friend " << T.money << endl;}

//class me;
//class key;

template <> //template specialization
void safe::backdoor<class key>()  //void safe::backdoor<class key>()
{
    // My specialization.
    money -= 100000;
    cout << "Template specialization " << money << "\n";
}

int main()
{
    safe s;
    s.backdoor<class key>();
    s.backdoor<key>();
    s.backdoor<int>();
    take(s); //error: ‘class safe’ has no member named ‘take’ just a friend not a member
}

Output: Constructor is called initializes 1000000 Template specialization 900000 Template specialization 800000 Template 750000 Friend 749999 In case of class Student before, using template specialization(empty template <>) can modify the private data members using template function is not compiled until an instantiation with specific template arguments is required.
#include <iostream>
#include <string>
using namespace std;

class Student {
     private:
     string name;
     int grade;
  public:
     void ShowStudent() { cout << name << " " << grade << endl;}
  template <typename T> //template
     void change(){ name = "Thomas"; grade = 9;}
 };
template <>  //template specialization
void Student::change<class modify>()  //void safe::backdoor<class key>()
{
    // My specialization.
    name = "Hacker";
    grade = 10;
    cout << "Template specialization " << "\n";
}

int main(){
  Student T;
  T.change<modify>();
  T.ShowStudent();
  T.change<int>();
  T.ShowStudent();
  return 0;
 }
Output: Hacker 10 Thomas 9

Saturday, June 09, 2012

Modify blogger template using add custom CSS

If you google most of people try to change HTML page of the blogger by editing the HTML page and you don't have to do it any more if you know how CSS works. There is a new feature called Add CSS.
In Template -> Customize ->Advanced ->Add CSS you can customize your CSS to override the current CSS of your current template. If you want to remove the top navbar and bottom footer-3 you target the ID enter as below, if you want to expanse the background to cover the whole page target on body and body class as below. Similar when you write code in Java/C++ you can override functions of the abstract base class. It is a bit complicate to find out the target id and class you need to use the tools: firebug or web developer. You can also look at by view source of your blogger in the browser or paste into Dreamweaver to figure out those id and class for the particular CSS that needed to change. When enter into add custom CSS you can see your blog changes right away if it is correct id or class. It likes a debug monitor.
To add permanent to the blog don't forget to apply by clicking "Apply to Blog."  This feature makes the blog as you want just changing the CSS style sheet. To change the HTML page is not a good choice unless you have to because you need to remember where those changes in a long HTML code page and sometimes it is confusing and complicated. With CSS you need to remember ID and class that need to change. In both cases you will need to know where the id or class have to be changed whether in HTML or CSS. In case of the template is changed in the future you just paste the CSS lines into Add Custom CSS then you're done. It is much quicker to add these CSS lines than go to HTML page and do the search then changing the sections of HTML.This is the cleanest way.
The only things that you can change HTML/JavaScript and now with CSS on the blogger. HTML/Javascript goes to Layout Add a Gadget then choose HTML/JavaScript to your blog. Then paste HTML or Javascript into this new gadget.

#footer-3, #navbar-iframe
{
  display: none;
}

body {
    -o-background-size: cover;
    background-size: cover;
}
.body-fauxcolumn-outer .cap-top {
    display:none;
}

Note:
# is ID, body is for element called in HTML .body for class body, target more then 1 element need to have comma between in the case  #footer-3, #navbar-iframe here we target 2 IDs: #footer and #navbar to display none. Only 3 lines of code to remove top va bottom of blogger. That is the magic of CSS.


Friday, June 08, 2012

Processes Vs. Threads revisited

http://objectlayer.blogspot.ca/2006/05/thread-vs-process.html
- All threads in a program must run the same executable.A child process, on the
other hand, may run a different executable by calling an exec function.
- An errant thread can harm other threads in the same process because threads
share the same virtual memory space and other resources. For instance, a wild
memory write through an uninitialized pointer in one thread can corrupt
memory visible to another thread.
An errant process, on the other hand, cannot do so because each process has a
copy of the program’s memory space.
- Copying memory for a new process adds an additional performance overhead
relative to creating a new thread. However, the copy is performed only when
the memory is changed, so the penalty is minimal if the child process only reads
memory.
- Threads should be used for programs that need fine-grained parallelism. For
example, if a problem can be broken into multiple, nearly identical tasks, threads
may be a good choice. Processes should be used for programs that need coarser
parallelism.
- Sharing data among threads is trivial because threads share the same memory.
(However, great care must be taken to avoid race conditions, as described previously.)
Sharing data among processes requires the use of IPC mechanisms, as
described in Chapter 5.This can be more cumbersome but makes multiple
processes less likely to suffer from concurrency bugs.
- Thread has its own Code, Data, Stack and Thread is sharing. Each Process has one or more threads and each thread belongs to one process
- Thread is fast for context switch and cheaper than process.
Conceptually, a thread exists within a process.Threads
Simple process for ls

#include <pthread.h>
int main()
{
  int return_value;
  return_value = system ("ls -l /");
  return return_value;
}



#include <pthread.h>
#include <stdio.h>
/* Prints x’s to stderr.*/
void* print_xs (void* unused)
{
    while (1)
    fputc ('x', stderr);
    return NULL;
}
/* The main program.
*/
int main ()
{
    pthread_t thread_id;
    /* Create a new thread. The new thread will run the print_xs
    function. */
    pthread_create (&thread_id, NULL, &print_xs, NULL);
    /* Print o’s continuously to stderr. */
    while (1)
    fputc ('o', stderr);
    return 0;
}
Compile and link this program using the following code:
$ gcc -o thread-create thread-create.c -lpthread
$ ./thread-create
ooooxxxxxxxxxxxxxxooooo

Is linux kernel preemptive or not?

Yes, the kernel is preemptive.
It has been preemptive by default since the 2.6 branch. The old Linux kernel is not preemptive, which means that a process can be preempted only while running in User Mode; non preemptive kernel design is much simpler, since most synchronization problems involving the kernel data structures are easily avoided Prior to Linux kernel version 2.5.4, Linux Kernel was not preemptive which means a process running in kernel mode cannot be moved out of processor until it itself leaves the processor or it starts waiting for some input output operation to get complete.
  Generally a process in user mode can enter into kernel mode using system calls. Previously when the kernel was non-preemptive, a lower priority process could priority invert a higher priority process by denying it access to the processor by repeatedly calling system calls and remaining in the kernel mode. Even if the lower priority process' timeslice expired, it would continue running until it completed its work in the kernel or voluntarily relinquished control. If the higher priority process waiting to run is a text editor in which the user is typing or an MP3 player ready to refill its audio buffer, the result is poor interactive performance. This way non-preemptive kernel was a major drawback at that time.
A preemptive kernel is one that can be interrupted in the middle of a executing code - for instance in response for a system call - to do other things and run other threads, possible that are not in the kernel.
The main advantage in a preemptive kernel is that sys-calls do not block the entire system. if a sys-call takes a long time to finish then it doesn't mean the kernel can't do anything else in this time.
The main disadvantage is that this introduces more complexity to the kernel code, having to handle more end-cases, perform more fine grained locking or use lock-less structures and algorithms.
preemption (more correctly pre-emption) is the act of temporarily interrupting a task being carried out by a computer system, without requiring its cooperation, and with the intention of resuming the task at a later time. Such a change is known as a context switch. It is normally carried out by a privileged task or part of the system known as a preemptive scheduler, which has the power to preempt, or interrupt, and later resume, other tasks in the system.
$ strace echo test                                
execve("/bin/echo", ["echo", "test"], [/* 45 vars */]) = 0       (execve, mmap are system calls)         
brk(0)                                  = 0xc90000  
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f4210db7000
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)         
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f4210db5000
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f4210c5d000
write(1, "test\n", 5test
)                   = 5
close(1)                                = 0
munmap(0x7f4210c5d000, 4096)            = 0
close(2)                                = 0
exit_group(0)                           = ?

Kernel space and user space


System calls are used when a user space program wants to use some data or some service provided by the Linux kernel. In current Linux kernel (2.6.23) there exist 324 system calls. All system calls provide a function which is useful for many application programs (such as file operations, network operations or process related operations). There is no point in adding a very specific system call which can be used only by a specific program. http://www.kernel.org/doc/man-pages/online/pages/man2/mknod.2.html
A conventional computer operating system usually segregates virtual memory into kernel space and user space. Kernel space is strictly reserved for running the kernel, kernel extensions, and most device drivers. In contrast, user space is the memory area where all user mode applications work and this memory can be swapped out when necessary.
Similarly, the term userland refers to all application software that runs in user space.[1] Userland usually refers to the various programs and libraries that the operating system uses to interact with the kernel: software that performs input/output, manipulates file system objects, etc.
Each user space process normally runs in its own virtual memory space, and, unless explicitly requested, cannot access the memory of other processes. This is the basis for memory protection in today's mainstream operating systems, and a building block for privilege separation. Depending on the privileges, processes can request the kernel to map part of another process's memory space to its own, as is the case for debuggers. Programs can also request shared memory regions with other processes.
Kernel space and user space is the separation of the privileged operating system functions and the restricted user applications. The separation is necessary to prevent user applications from ransacking your computer. It would be a bad thing if any old user program could start writing random data to your hard drive or read memory from another user program's memory space.
User space programs cannot access system resources directly so access is handled on the program's behalf by the operating system kernel. The user space programs typically make such requests of the operating system through system calls.


Write a device driver in Linux

/* Necessary includes for device drivers http://www.freesoftwaremagazine.com/articles/drivers_linux?page=0%2C1 */

#include <linux init.h>

//#include <linux config.h> no more since 2.6.19 deprecated

#include <linux module.h>

#include <linux kernel.h> /* printk() */

#include <linux slab.h> /* kmalloc() */

#include <linux fs.h> /* everything... */

#include <linux errno.h> /* error codes */

#include <linux types.h> /* size_t */

#include <linux proc_fs.h>

#include <linux fcntl.h> /* O_ACCMODE */

#include <asm system.h> /* cli(), *_flags */

#include <asm uaccess.h> /* copy_from/to_user */



MODULE_LICENSE("Dual BSD/GPL");



/* Declaration of memory.c functions */

int memory_open(struct inode *inode, struct file *filp);

int memory_release(struct inode *inode, struct file *filp);

ssize_t memory_read(struct file *filp, char *buf, size_t count, loff_t *f_pos);

ssize_t memory_write(struct file *filp, char *buf, size_t count, loff_t *f_pos);

void memory_exit(void);

int memory_init(void);



/* Structure that declares the usual file */

/* access functions */

struct file_operations memory_fops = {

  read: memory_read,

  write: memory_write,

  open: memory_open,

  release: memory_release

};



/* Declaration of the init and exit functions */

module_init(memory_init);

module_exit(memory_exit);



/* Global variables of the driver */

/* Major number */

int memory_major = 60;

/* Buffer to store data */

char *memory_buffer;



int memory_init(void) {

  int result;



  /* Registering device */

  result = register_chrdev(memory_major, "memory", &memory_fops);

  if (result < 0) {

    printk(

      "<1>memory: cannot obtain major number %d\n", memory_major);

    return result;

  }



  /* Allocating memory for the buffer */

  memory_buffer = kmalloc(1, GFP_KERNEL); 

  if (!memory_buffer) { 

    result = -ENOMEM;

    goto fail; 

  } 

  memset(memory_buffer, 0, 1);



  printk("<1>Inserting memory module\n"); 

  return 0;



  fail: 

    memory_exit(); 

    return result;

}



void memory_exit(void) {

  /* Freeing the major number */

  unregister_chrdev(memory_major, "memory");



  /* Freeing buffer memory */

  if (memory_buffer) {

    kfree(memory_buffer);

  }



  printk("<1>Removing memory module\n");



}



int memory_open(struct inode *inode, struct file *filp) {



  /* Success */

  return 0;

}

int memory_release(struct inode *inode, struct file *filp) {



  /* Success */

  return 0;

}

ssize_t memory_read(struct file *filp, char *buf, 

                    size_t count, loff_t *f_pos) { 



  /* Transfering data to user space */ 

  copy_to_user(buf,memory_buffer,1);



  /* Changing reading position as best suits */ 

  if (*f_pos == 0) { 

    *f_pos+=1; 

    return 1; 

  } else { 

    return 0; 

  }

}

ssize_t memory_write( struct file *filp, char *buf,

                      size_t count, loff_t *f_pos) {



  char *tmp;



  tmp=buf+count-1;

  copy_from_user(memory_buffer,tmp,1);

  return 1;

}

///----Makefile
obj-m = hello.o memory.o
KVERSION = $(shell uname -r)
all:
    make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules
clean:
    make -C /lib/modules/$(KVERSION)/build M=$(PWD) clean
///----Testing after make
$sudo nsmod memory.ko
$sudo rmmod memory.ko
$ dmesg | less
[223447.209899] Inserting memory module
[223629.779878] Removing memory module
[223663.099549] Loading hello module...
# mknod /dev/memory c 60 0 (make device using system call see http://www.kernel.org/doc/man-pages/online/pages/man2/mknod.2.html  In the above, c means that a char device is to be created, 60 is the major number and 0 is the minor number.)
Insert character into the device
#chmod 666 /dev/memory
#insmod memory.ko
#echo -n ABC > /dev/memory
#cat /dev/memory
C
Note: .ko kernel object,.so /usr/lib (library), .ro (module plugin gedit)
.o for object then link gcc -o test test.c

Questions:
Q. Can you explain me what is device files and how do I access or see device files? Why UNIX / Linux has device files?
A. Under Linux and UNIX each and every hardware device treated as a file. A device file allows to accesses hardware devices so that end users do not need to get technical details about hardware.
In short, a device file (also called as a special file) is an interface for a device driver that appears in a file system as if it were an ordinary file. This allows software to interact with the device driver using standard input/output system calls, which simplifies many tasks.

Device file two types

There are two types of device files based upon how data written to them and read from them is processed by the operating system and hardware:
  • Character special files or Character devices
  • Block special files or Block devices

Understanding Character special files or Character devices

  • Talks to devices in a character by character (1 byte at a time)
  • Examples: Virtual terminals, terminals and serial modems etc

Understanding Block special files or Block devices

  • Talks to devices 1 block at a time ( 1 block = 512 bytes to 32KB)
  • Examples: Hard disk, DVD/CD ROM, and memory regions etc

Why use device files?

Device file allows transparent communication between user space applications and computer hardware.

What is a Zombie process?

http://en.wikipedia.org/wiki/Zombie_process On Unix and Unix-like computer operating systems, a zombie process or defunct process is a process that has completed execution but still has an entry in the process table. This entry is still needed to allow the parent process to read its child's exit status. The term zombie process derives from the common definition of zombie — an undead person. In the term's metaphor, the child process has "died" but has not yet been "reaped". Also, unlike normal processes, the kill command has no effect on a zombie process.

How do I kill zombie process?

You cannot kill zombies, as they are already dead. But if you have too many zombies then kill parent process or restart service.
You can kill zombie process using PID obtained from any one of the above command. For example kill zombie process having PID 4104:
# kill -9 4104
create zombie.c

#include <stdlib.h&g

#include <sys types.h&g

#include <unistd.h&g



int main ()

{

pid_t child_pid;



child_pid = fork (); // system call to create a new process referred to as the child process

if (child_pid > 0) {

sleep (60);

}

else {

exit (0);                  // parent exist make child becomes zombie if the parent crashes makes it becomes

}                             // orphan process will waste resources but zombie is no harm except running out PID

return 0;

}

gcc zombie.c -o zombie
./zombie
after 1 minute
ps -ax
  1815 ?        Sl     0:00 /usr/bin/python /usr/bin/bzr-notify
 6314 pts/1    S+     0:00 ./zombie
 6315 pts/1    Z+     0:00 [zombie]
The child process is marked as , and its status code is Z, for zombie.
When the program exits, the child process is inherited by init. This process should cleans up the zombie proces automatically.

Zombie vs. Orphan process

http://en.wikipedia.org/wiki/Zombie_process
On Unix and Unix-like computer operating systems, a zombie process or defunct process is a process that has completed execution but still has an entry in the process table. This entry is still needed to allow the parent process to read its child's exit status. The term zombie process derives from the common definition of zombie — an undead person. In the term's metaphor, the child process has "died" but has not yet been "reaped". Also, unlike normal processes, the kill command has no effect on a zombie process.
A zombie process is not the same as an orphan process. An orphan process is a process that is still executing, but whose parent has died. They do not become zombie processes; instead, they are adopted by init (process ID 1), which waits on its children.