“Hello world” kernel module

Make a directory called “helloM” in your home dir and edit the following .C file, called “hello.c”:

/*hello.c – The simplest kernel module.*/

#include <linux/module.h>  /* Needed by all modules */
#include <linux/kernel.h>  /* Needed for KERN_ALERT */


int init_module(void)
{
printk("<1>Hello world 1.\n");
// A non 0 return means init_module failed; module can't be loaded.
return 0;
}

void cleanup_module(void)
{
printk(KERN_ALERT "Goodbye world 1.\n");
}

To compile this kernel module you need to edit the following “Makefile” (called “Makefile” !):

ifneq ($(KERNELRELEASE),)

# We were called by kbuild

obj-m += hello.o

else  # We were called from command line

KDIR := /lib/modules/$(shell uname -r)/build

#KDIR := /home/cynove/src/kernel/linux-source-2.6.31

PWD  := $(shell pwd)

default:

@echo '    Building target module 2.6 kernel.'

@echo '    PLEASE IGNORE THE "Overriding SUBDIRS" WARNING'+

$(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules

install:

./do_install.sh *.ko

endif  # End kbuild check

######################### Version independent targets ##########################

clean:

rm -f -r *.o *.ko .*cmd .tmp* core *.i

Then, within our working folder, type make, which will process the Makefile and create a module file, hello.ko.

To install the module,type:

sudo insmod hello.ko

To verify the module has output to the log file in Ubuntu 11.10 type:

 tail /var/log/kern.log
 

You should read the message of the init_module() method, that is “Hello world 1.”

To remove the module, type:

sudo rmmod hello.ko

In the tail of the kern.log you should find “Goodbye world 1.”.

Funny! By these first steps you can make interesting kernel modules!

Recursive Beer Ballad

Even though I’ve been into Java since 2007, I had never found out how recursion can be powerful when you have to print several lines of code…

So now I’ve just made a funny little programs with a recursive method.

Separating the cases by a switch, this funny Beer Ballad plays even better!

Check it out!

—————————————————–// BeerBallad.java”//———————




import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Beer {

public static void balladCounter(int n) {
switch(n){
case 0:  System.out.println("No bottles of beer on the wall, no bottles of beer, ya’ can’t take one down, ya’    can’t pass it around, ’cause there are no more bottles of beer on the wall! \n"); break;
case 1:  System.out.println("1 bottle of beer on the wall, 1 bottle of beer,  ya’ take one down, ya’ pass it around, and now there are no more bottles of beer on the wall! \n");
balladCounter(n-1);   break;
case 2:    System.out.println("2 bottles of beer on the wall, 2 bottles of beer,  ya’ take one down, ya’ pass it around, and now just 1 bottle of beer on the wall! \n");
balladCounter(n-1);     break;
default:     // if n>2
System.out.println(n+" bottles of beer on the wall, "+n+" bottles of beer, ya’ take one down, ya’ pass it around, "+(n-1)+" bottles of beer on the wall. \n");
balladCounter(n-1);    break;
}
}

public static void main(String[] args) {
int m = 0;   //input from console
String inputString = null;
BufferedReader bufferedReader = null;
System.out.println("How many beers do you want to sing about?");
bufferedReader = new BufferedReader(new InputStreamReader(System.in));

try { inputString = bufferedReader.readLine();


m = Integer.parseInt(inputString);

System.out.println("\n THE BALLAD OF THE BEER \n");
balladCounter(m); }
catch (IOException e) { e.printStackTrace();}
}
} 

Perl script using LWP module

Library FOR WWW in Perl (LWP)

In Linux you can istall all the perl modules about the web (LWP, URI, URL, HTTP…) at once:

:~$ sudo apt-get install libwww-perl

LWP is the most used Perl module for accessing data on the web.

LWP::Simple – module to get document by http
its functions don’t support cookies or authorization, setting header lines in the HTTP request; and generally, they don’t support reading header lines in the HTTP response (most notably the full HTTP error message, in case of an error). To get at all those features, you’ll have to use the LWP::UserAgent;

LWP::UserAgent is a class for “virtual browsers,” which you use for performing requests, and HTTP::Response is a class for the responses (or error messages) that you get back from those requests.

There are two objects involved: $browser, which holds an object of the class LWP::UserAgent, and then the $response object, which is of the class HTTP::Response. You really need only one browser object per program; but every time you make a request, you get back ar esponse object, which will have some interesting attributes:

$response->is_success : A HTTP status line, indicating success or failure  (like “404 Not Found”).

$response->content_type A MIME content-type like “text/html”, “image/gif”, “application/xml”, and so on, which you can see with

$response->content : the actual content of the response. If the response is HTML, that’s where the HTML source will be; if it’s a GIF, then $response->content will be the binary GIF data.

Enabling Cookies

A default LWP::UserAgent object acts like a browser with its cookies support turned off.
You can even activate cookies, with the following function:

$browser->cookie_jar({});

with “cookie_jar” you can get and save the cookies from Browsers.

The following script gets a url from the shell and print the content of the corresponding web page both to screen and a new file called “code.html” (created by running the script).

———————————————————-webclient.pl———————————–

#!/usr/bin/perl -w
use LWP::UserAgent;

#browser = instance of the UserAgent class
my $browser = LWP::UserAgent->new;
my $url =$ARGV[0]; # passing the url by command line
my $response = $browser->get($url);

die "Can’t get $url \n", $response->status_line
unless $response->is_success;

# check if the content is html
die "Hey, I was expecting HTML, not ", $response->content_type
unless $response->content_type eq 'text/html';

print "Page content: \n";

#print content to console
print $response->decoded_content;

#print content to a NEW file
open (MYPAGE, '>>code.html');
print MYPAGE $response->decoded_content;
close (MYPAGE);

#REGULAR EXPRESSION: search for a string in the content
if($response->content =~ m/perl/i) {
print " \n \n This page is about Perl!\n \n";
} else {print "\n \n No content about Perl! \n \n"; }

Linux file system

filesystem: the files and directories (or folders), the method used to store data on the hard drive (such as the ext3 filesystem.

– Windows keeps all the important system files in a single directory C:\
– Linux follows the lead of its UNIX
– Windows and Linux setups are both logical

✓ Linux uses a forward slash (/) between directories, not the backslash (\) that Windows uses. So, the file yum.conf in the directory etc is
etc/yum.conf.

✓ Files and directories can have names up to 256 characters long, and these names can contain underscores (_), dashes (-), and dots (.) any-
where within. So my.big.file or my.big_file or my-big-file are all valid filenames.

✓ Upper- and lowercase matter. They have to match exactly. The files yum.conf and Yum.conf are not the same as far as Linux is concerned.
Linux is case-sensitive — it pays attention to the case of each character. Windows, on the other hand, is case-insensitive.

✓ The same filesystem can span multiple partitions, hard drives, and media (such as CD-ROM drives). You just keep going down through
subdirectories, not having to care whether something is on disk A, B, or whatever.

Everything in the Linux filesystem is relative to the root directory — not to be confused with the system Administrator, who is the root user. The root directory is referred to as /, and it is the filesystem’s home base — a doorway into all your files. As such, it contains a relatively predictable set of subdirectories. Each distribution varies slightly in terms of what it puts in the root directory. More or less you can find the following directories.

/bin   : Essential commands that everyone needs to use at any time.*
/boot  : The information that boots the machine, including your kernel.*
/dev :  The device drivers for all the hardware that your system needs to  interface with.*
/etc  : The configuration files for your system.*
/home  : The home directories for each of your users.
/lib  : The libraries, or the code that many programs (and the kernel) use.*
/media  : A spot where you add temporary media, such as floppy disks and  CD-ROMs; not all distributions have this directory.
/mnt  :  A spot where you add extra filesystem components such as networked drives and items you aren’t permanently adding to your filesystem but that aren’t as temporary as CD-ROMs and floppies.
/opt   : The location that some people decide to use (and some programs want to use) for installing new software packages, such as word
processors and office suites.
/proc   : Current settings for your kernel (operating system).*
/root   : The superuser’s (root user’s) home directory.
/sbin   : The commands the system Administrator needs access to.*
/srv   : Data for your system’s services (the programs that run in thebackground).*
/sys   : Kernel information about your hardware.*
/tmp   : The place where everyone and everything stores temporary files.
/usr   : A complex hierarchy of additional programs and files.
/var   : The data that changes frequently, such as log files and your mail.

Most common linux file extensions

There is no .exe equivalent in linux. Executables are denoted by file permissions, not extensions. In directories such as /etc, many files do not use a file extension because it is in /etc it is assumed to be a configuration (ASCII text) file.

Ex. “RELEASE NOTE” is the correct name for a file (remember that it’s case sensitive).

The following list shows the most commons file extensions for linux:

.a   : a static library ;
.au    : an audio file ;
.bin :    a) a binary image of a CD (usually a .cue file is also included); b) represents that the file is binary and is meant to be executed ;
.bz2 :    A file compressed using bzip2 ;
.c :    A C source file ;
.conf :  A configuration file. System-wide config files reside in /etc while any user-specific configuration will be somewhere in the user’s home directory ;
.cpp :  A C++ source file ;
.deb :  a Debian Package;
.diff :   A file containing instructions to apply a patch from a base version to another version of a single file or a project (such as the linux kernel);
.dsc:   a Debian Source information file ;
.ebuild : Bash script used to install programs through the portage system. Especially prevalent on Gentoo systems;
.el :  Emacs Lisp code file;
.elc :  Compiled Emacs Lisp code file;
.gif :    a graphical or image file;
.h :a C or C++ program language header file;
.html/.htm  :   an HTML file;
.iso :    A image (copy) of a CD-ROM or DVD in the ISO-9660 filesystem format;
.jpg :    a graphical or image file, such as a photo or artwork;
.ko :    The kernel module extension for the 2.6.x series kernel;
.la :    A file created by libtool to aide in using the library;
.lo :    The intermediate file of a library that is being compiled;
.lock :    A lock file that prevents the use of another file;
.log :    a system or program’s log file;
.m4 :    M4 macro code file;
.o :    1) The intermediate file of a program that is being compiled ; 2) The kernel module extension for a 2.4 series kernel ; 3)a program object file;
.pdf :    an electronic image of a document;
.php :     a PHP script;
.pid :    Some programs write their process ID into a file with this extention;
.pl :    a Perl script;
.png :    a graphical or image file;
.ps :    a PostScript file; formatted for printing;
.py :    a Python script;
.rpm :    an rpm package. See Distributions of Linux for a list of distributions that use rpms as a part of their package management system;
.s :    An assembly source code file;
.sh :    a shell script;
.so :     a Shared Object, which is a shared library. This is the equivalent form of a Windows DLL file;
.src  :    A source code file. Written in plain text, a source file must be compiled to be used;
.sfs :    Squashfs filesystem used in the SFS Technology;
.tar.bz2 , tbz2, tar.gz :     a compressed file per File Compression;
.tcl :    a TCL script;
.tgz :     a compressed file per File Compression. his may also denote a Slackware binary or source package;
.txt :    a plain ASCII text file;
.xbm :    an XWindows Bitmap image;
.xpm :     an image file;
.xcf.gz, xcf :  A GIMP image (native image format of the GIMP);
.xwd :    a screenshot or image of a window taken with xwd;
.zip :extension for files in ZIP format, a popular file compression format;
.wav :    an audio file.

Linux archives file extensions

Although rar and zip files are supported, linux has its on archive file extensions too.
When you’re looking for software or when you need to save yourself some space, you can find files with the following extension:

A tarball is a bunch of files (and possibly directories) packaged together in a .tar file and compressed using the gzip utility; the
tarball then contains the .tar.gz extension.

.tar : A bunch of files bundled together
.tar.bz2  :  A tarball (a .tar file inside a .bz2 file. )
.tar.gz : A traditional tarball, which is a .tar file inside a .gz file.

Program (shell command): tar, bzip2, gunzip,gzip.

Other archive extensions are: .deb, and .rpm

.deb : All the files related to an application bundled together using a Debian-specific   format, used in Ubuntu and gOS.
Program (shell command): dpkg, apt-get, zipper (for open suse distributions).

.rpm : All the files related to a single application bundled together using a format designed by Red Hat and used in Fedora.
Program (shell command): rmp, yum

 

Perl script for a Hollywood Sqlite database

Let’s analyze the following perl scripta “cinema.pl”, to create and populate a simple database about  movies, and “query_hollywood.pl” to execute a simple SELECT-FROM-WHERE query on it.

—————————————cinema.pl————————————————————

#!/usr/bin/perl -w

use DBI;
use strict;

# CONFIG VARIABLES
my $platform = “SQLite”;
my $database = “hollywood.db”;
my $host = “localhost”;
my $port = “3306”;
my $user = “username”;
my $pw = “password”;

# DATA SOURCE NAME
my $dsn = “dbi:$platform:$database:$host:$port”;

# PERL DBI CONNECT
my $dbh = DBI->connect($dsn, $user, $pw) or die “Cannot connect: $DBI::errstr”;

# creating the “hollywood” database
$dbh->do(“CREATE TABLE IF NOT EXISTS actors(aid integer primary key, name text)”);

$dbh->do(“CREATE TABLE IF NOT EXISTS  movies(mid integer primary key, title text)”);

$dbh->do(“CREATE TABLE IF NOT EXISTS actors_movies(id integer primary key, mid integer, aid integer)”);

#populating “actors” table
$dbh->do(“INSERT INTO actors(name) VALUES(‘Philip Seymour Hofman’)”);
$dbh->do(“INSERT INTO actors(name) VALUES(‘Kate Shindle’)”);
$dbh->do(“INSERT INTO actors(name) VALUES (‘Kelci Stephenson’)”);
$dbh->do(“INSERT INTO actors(name) VALUES(‘Al Pacino’)”);
$dbh->do(“INSERT INTO actors(name) VALUES(‘Gabrielle Anwar’)”);
$dbh->do(“INSERT INTO actors(name) VALUES(‘Patricia Arquette’)”);
$dbh->do(“INSERT INTO actors(name) VALUES(‘Gabriel Byrne’)”);
$dbh->do(“INSERT INTO actors(name) VALUES(‘Max von Sydow’)”);
$dbh->do(“INSERT INTO actors(name) VALUES(‘Ellen Burstyn’)”);
$dbh->do(“INSERT INTO actors(name) VALUES(‘Jason Miller’)”);

#populating “movies” table

$dbh->do(“INSERT INTO movies VALUES(1,’Capote’)”);
$dbh->do(“INSERT INTO movies VALUES(2,’Scent of a woman’)”);
$dbh->do(“INSERT INTO movies VALUES(3,’Stigmata’)”);
$dbh->do(“INSERT INTO movies VALUES(4,’Exorcist’)”);
$dbh->do(“INSERT INTO movies VALUES(5,’Hamsun’)”);

#populating “actorsMovies” table
$dbh->do(“INSERT INTO actors_movies VALUES(1,1,1)”);
$dbh->do(“INSERT INTO actors_movies VALUES(2,2,1)”);
$dbh->do(“INSERT INTO actors_movies VALUES(3,3,1)”);
$dbh->do(“INSERT INTO actors_movies VALUES(4,4,2)”);
$dbh->do(“INSERT INTO actors_movies VALUES(5,5,2)”);
$dbh->do(“INSERT INTO actors_movies VALUES(6,6,3)”);
$dbh->do(“INSERT INTO actors_movies VALUES(7,7,3)”);
$dbh->do(“INSERT INTO actors_movies VALUES(8,8,4)”);
$dbh->do(“INSERT INTO actors_movies VALUES(9,9,4)”);
$dbh->do(“INSERT INTO actors_movies VALUES(10,10,4)”);
$dbh->do(“INSERT INTO actors_movies VALUES(11,8,5)”);

print qq{“Hollywood” database created! \n };

$dbh->disconnect;

—————————————————query_hollywood.pl———————————————

#!/usr/bin/perl -w

use DBI;
use strict;

# CONFIG VARIABLES
my $platform = “SQLite”;
my $database = “hollywood.db”;
my $host = “localhost”;
my $port = “3306”;
my $user = “username”;
my $pw = “password”;

# DATA SOURCE NAME
my $dsn = “dbi:$platform:$database:$host:$port”;

# PERL DBI CONNECT
my $dbh = DBI->connect($dsn, $user, $pw) or die “Cannot connect: $DBI::errstr”;

# EXECUTE THE QUERY
my $query = “SELECT actors.name , movies.title  FROM actors,movies,actors_movies WHERE actors.aid=actors_movies.aid and
movies.mid=actors_movies.mid”;

my $sth=$dbh->selectall_arrayref($query);

print “Actor                                                          Movie \n” ;
print “======================  ====================\n”;

foreach my $row (@$sth) {
my ($name, $title) = @$row;

### Print out the table metadata…
printf “%-23s %-23s \n”, $name, $title;

}

$dbh->disconnect;

—————————————————————————————–

Make the perl scripts executable like:
$ sudo chmod +x script.pl

And run them liket:
$ ./script.pl

The result of the query is:

Actor                                   Movie
====================  ====================
Philip Seymour Hofman     Capote
Philip Seymour Hofman     Scent of a woman
Philip Seymour Hofman     Stigmata
Kate Shindle                      Exorcist
Kate Shindle                      Hamsun

 

Very nice script, isn’t it?
I guess the DBI deserves further attention…

Sqlite database backup: the .dump command

Let’s go on mastering our sqlite3 knowledge.
SQLite database is really just a file: a backup it’s as simple as copying one file.

The .dump command shows information about all the changes performed onto the database. Less pieces of information to the hidden file can be found in your home/user typing: $ ~/.sqlite_history.

$ sqlite3 test.db “.dump”

The result is:
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE n(id INTEGER PRIMARY KEY, f TEXT, l TEXT);
INSERT INTO “n” VALUES(1,’linus’,’torvalds’);
INSERT INTO “n” VALUES(2,’richard’,’stallman’);
COMMIT;

If you want to backup the database in a new file, you can specify a name (ex. “dbbackup”):
$ $ sqlite3 test.db ‘.dump’ > dbbackup

The contents of the backup can be modified.
For example you can filter and pipe it to another database. Below, table “n” is changed to “people” with the sed command, and it is piped into the “computer_pioneers” database.

$ sqlite3 test.db “.dump”|sed -e s/n/people/|sqlite3 computer_pioneers.db
The contect is the same:
$sqlite3 computer_pioneers.db “select * from people”;

We use cookies to personalise content and ads, to provide social media features and to analyse our traffic. We also share information about your use of our site with our social media, advertising and analytics partners.
Cookies settings
Accept
Privacy & Cookie policy
Privacy & Cookies policy
Cookie name Active

Privacy Policy

What information do we collect?

We collect information from you when you register on our site or place an order. When ordering or registering on our site, as appropriate, you may be asked to enter your: name, e-mail address or mailing address.

What do we use your information for?

Any of the information we collect from you may be used in one of the following ways: To personalize your experience (your information helps us to better respond to your individual needs) To improve our website (we continually strive to improve our website offerings based on the information and feedback we receive from you) To improve customer service (your information helps us to more effectively respond to your customer service requests and support needs) To process transactions Your information, whether public or private, will not be sold, exchanged, transferred, or given to any other company for any reason whatsoever, without your consent, other than for the express purpose of delivering the purchased product or service requested. To administer a contest, promotion, survey or other site feature To send periodic emails The email address you provide for order processing, will only be used to send you information and updates pertaining to your order.

How do we protect your information?

We implement a variety of security measures to maintain the safety of your personal information when you place an order or enter, submit, or access your personal information. We offer the use of a secure server. All supplied sensitive/credit information is transmitted via Secure Socket Layer (SSL) technology and then encrypted into our Payment gateway providers database only to be accessible by those authorized with special access rights to such systems, and are required to?keep the information confidential. After a transaction, your private information (credit cards, social security numbers, financials, etc.) will not be kept on file for more than 60 days.

Do we use cookies?

Yes (Cookies are small files that a site or its service provider transfers to your computers hard drive through your Web browser (if you allow) that enables the sites or service providers systems to recognize your browser and capture and remember certain information We use cookies to help us remember and process the items in your shopping cart, understand and save your preferences for future visits, keep track of advertisements and compile aggregate data about site traffic and site interaction so that we can offer better site experiences and tools in the future. We may contract with third-party service providers to assist us in better understanding our site visitors. These service providers are not permitted to use the information collected on our behalf except to help us conduct and improve our business. If you prefer, you can choose to have your computer warn you each time a cookie is being sent, or you can choose to turn off all cookies via your browser settings. Like most websites, if you turn your cookies off, some of our services may not function properly. However, you can still place orders by contacting customer service. Google Analytics We use Google Analytics on our sites for anonymous reporting of site usage and for advertising on the site. If you would like to opt-out of Google Analytics monitoring your behaviour on our sites please use this link (https://tools.google.com/dlpage/gaoptout/)

Do we disclose any information to outside parties?

We do not sell, trade, or otherwise transfer to outside parties your personally identifiable information. This does not include trusted third parties who assist us in operating our website, conducting our business, or servicing you, so long as those parties agree to keep this information confidential. We may also release your information when we believe release is appropriate to comply with the law, enforce our site policies, or protect ours or others rights, property, or safety. However, non-personally identifiable visitor information may be provided to other parties for marketing, advertising, or other uses.

Registration

The minimum information we need to register you is your name, email address and a password. We will ask you more questions for different services, including sales promotions. Unless we say otherwise, you have to answer all the registration questions. We may also ask some other, voluntary questions during registration for certain services (for example, professional networks) so we can gain a clearer understanding of who you are. This also allows us to personalise services for you. To assist us in our marketing, in addition to the data that you provide to us if you register, we may also obtain data from trusted third parties to help us understand what you might be interested in. This ‘profiling’ information is produced from a variety of sources, including publicly available data (such as the electoral roll) or from sources such as surveys and polls where you have given your permission for your data to be shared. You can choose not to have such data shared with the Guardian from these sources by logging into your account and changing the settings in the privacy section. After you have registered, and with your permission, we may send you emails we think may interest you. Newsletters may be personalised based on what you have been reading on theguardian.com. At any time you can decide not to receive these emails and will be able to ‘unsubscribe’. Logging in using social networking credentials If you log-in to our sites using a Facebook log-in, you are granting permission to Facebook to share your user details with us. This will include your name, email address, date of birth and location which will then be used to form a Guardian identity. You can also use your picture from Facebook as part of your profile. This will also allow us and Facebook to share your, networks, user ID and any other information you choose to share according to your Facebook account settings. If you remove the Guardian app from your Facebook settings, we will no longer have access to this information. If you log-in to our sites using a Google log-in, you grant permission to Google to share your user details with us. This will include your name, email address, date of birth, sex and location which we will then use to form a Guardian identity. You may use your picture from Google as part of your profile. This also allows us to share your networks, user ID and any other information you choose to share according to your Google account settings. If you remove the Guardian from your Google settings, we will no longer have access to this information. If you log-in to our sites using a twitter log-in, we receive your avatar (the small picture that appears next to your tweets) and twitter username.

Children’s Online Privacy Protection Act Compliance

We are in compliance with the requirements of COPPA (Childrens Online Privacy Protection Act), we do not collect any information from anyone under 13 years of age. Our website, products and services are all directed to people who are at least 13 years old or older.

Updating your personal information

We offer a ‘My details’ page (also known as Dashboard), where you can update your personal information at any time, and change your marketing preferences. You can get to this page from most pages on the site – simply click on the ‘My details’ link at the top of the screen when you are signed in.

Online Privacy Policy Only

This online privacy policy applies only to information collected through our website and not to information collected offline.

Your Consent

By using our site, you consent to our privacy policy.

Changes to our Privacy Policy

If we decide to change our privacy policy, we will post those changes on this page.
Save settings
Cookies settings