Saturday, 5 April 2008

Debugging with LINUX environment


Introduction


Linux environment generally used the GNU debugger, or gdb to the shell. Gdb lets you see the internal structure of a program, print out variable values, set breakpoints and single step through source code. It makes an extremely powerful tool for fixing problems in program code. In this article , Let's discuss how to use the .


The Linux development environment has several debugging alternatives. This
article I also explore debugging tools available for debugging applications, ranging
from simple print-statement to specialized tools (e.g. memory-debugging).


Print statements
Addition of printf() statements to your code is a traditional and time-honored way
to debug code. Downside is that you will need to modify and recompile the code
whenever you want more or less debug information.

Strace utility
Strace will output all the kernel calls that the application does and is a great way to find
e.g. what file the program is trying to access and whether it succeeded. For instance
calls to read() and write() will show how much data program tried to read/write and
how much actually was transferred, it also shows the beginning of the data in question.
You can use this without recompilations and it works on any program which you can
run.


Ltrace utility
Ltrace will output all the dynamic library function calls that the application does. It
can also show system calls like ’strace’.

Using GDB debugger
With gdb debugger you can examine all the symbols in the program and program runtime
state and follow program function calls. If trace utilities and the source code don’t
give you enough information to solve the problem, debugger is the next step. Gdb is
a console tool, but there are some nice debugging GUIs available that work on top of
gdb. One such is ddd.


Gdb can help with debugging programs written in C, C++, Fortran, Java, Chill, assembly
and Modula-2. You need to have compiled these programs with the gnu compiler
collection (gcc) tools.

Besides supporting multiple languages gdb also supports multiple hardware architectures,
including several embedded hardware architectures. It’s also possible to compile
a special version of GDB for debugging (Linux) kernel code.

Running gdb
Gdb is run from the shell with the command 'gdb' with the program name as a parameter, for example 'gdb file, or you can use the file command once inside gdb to load a program for debugging, for example 'file file. Both of these assume you execute the commands from the same directory as the program. Once loaded, the program can be started with the gdb command 'run'.


Preparing for GDB use
You need to compile all the C/C++ code you want to debug with debugging information
included into the binary (use ’-g’ and do not use ’-fomit-frame-pointer’ option when
compiling the code) and the code may not be stripped of symbols (do not use ’-s’ flag
in the compilation). Note that all the libraries used by the program should also be
compiled this way as missing stack frame pointer can confuse GDB.
It’s better if you use static linking (e.g. use ’-static’ option in your Makefile) because
that way gdb won’t have trouble finding the symbols for the libraries program uses (for
example if you use different libraries with your program than what your compilation
machine normally uses).

Before you can get started, the program you want to debug has to be compiled with debugging information in it. This is so gdb can work out the variables, lines and functions being used. To do this, compile your program under gcc (or g++) with an extra '-g' option:
gcc -g file.cpp -o file



Using GDB
There are two ways to use a debugger:
- Using debugger to examine the code runtime behavior. You start ’gdb’ with the
program binary (’gdb ’) in the program directory. Then you can either
run the program inside the gdb with ’run ’ or attach to an
already running instance of the program with ’attach ’. Latter is handy
when you don’t have working gdb inside the debugging environment. Then you
can set breakpoints, examine the code, variables, stack etc and call the program
functions.


- Using debugger to examine a process post-mortem ’core’ dump. You start ’gdb’
with the program binary and core dump (’gdb ’) in the program
code directory. You can examine where the program crashed and what was the
state of all the program variables. If your program crashes, but doesn’t produce
a core file, check ’ulimit -a’ to see whether your environment allows core files
and fix it with ’ulimit -c unlimited’.


The downside of debugger approach is that debug versions of the binaries are large and
statically linked debug ones are huge. If the target doesn’t have enough memory for
this, you can use ’gdbserver’ and stripped binaries on the target. On the host on which
you do the debugging, you use gdb with ’target remote’ option and give the host gdb
the binary with all the debugging symbols.

Short introduction to use of gdb

You get back to GDB prompt when your program either:
- Crashes.
- Code execution reaches a breakpoint.
- You suspend or otherwise send a signal to the program.

On latter two cases you can use ’cont’ to continue the program execution.


In the GDB prompt you can do one of the following:
- Set a breakpoint with ’break ’. You can delete breakpoint by
saying ’delete ’.
- Examine current program execution trace with ’bt’, which will show you where
the program execution was interrupted (see above), how it got there and what
were the function arguments.
- Move up and down in the execution stack frame by typing ’up’ or ’down’.
- Examine program state with either ’info locals’ which shows you the state of
variables in the current context (function) or use ’print ’ to show
you a value of given variable or function. Any valid C expression can be used,
even function calls!
- View your program code with ’list ’ which will list code of the
given function.
You can ’step’ through the program code with following commands:
- ’step’ will execute the current line and go to next command. If code line is a
function call, step will enter the function.
- ’next’ works like ’step’ but function calls are executed as single instruction.
- ’finish’ will execute to the end of current scope (function).
- ’cont’ will continue program execution.
Typing return will repeat the previous command. Gdb can also complete function and
variable names with TAB key.

Gdb problems
When optimization is used in code compilation, variable values shown by gdb may
sometimes be valid only for variables used on the line that program executed lastly 1,
not for the whole scope in where the variables are declared. Use of inlines especially
in C++ code (e.g. methods with their body in the header file) may confuse gdb so that
it shows either a wrong filename or line for the fault.
In these cases it’s better not to optimize the code so much, use only ’-O’ optimization
flag, and forbid inlining completely with the ’-fno-default-inline’ compilation flag.

Friday, 4 April 2008

Frequently asked interview question in Unix

Most commonly asked Questions in Unix.

I bet if any one would get prepared with these questions . One would have win the half of the battle of Interview war.

1) Advantages/disadvantages of script vs compiled program.

2) Name a replacement for PHP/Perl/MySQL/Linux/Apache and show main differences.

3) Why have you choosen such a combination of products?

4) Differences between two last MySQL versions. Which one would you choose and when/why?

5) Main differences between Apache 1.x and 2.x. Why is 2.x not so popular?
Which one would you choose and when/why?

6) Which Linux distros do you have experience with?

7) Which distro you prefer? Why?

8) Which tool would you use to update Debian / Slackware / RedHat / Mandrake / SuSE ?9)
You're asked to write an Apache module. What would you do?

10) Which tool do you prefer for Apache log reports?

11) What does 'route' command do?

12) Differnces between ipchains and iptables.

13) What's eth0, ppp0, wlan0, ttyS0, etc.

14) What are different directories in / for?

15) Partitioning scheme for new webserver. Why?

16) What is a Make file?

17) Could you tell something about the Unix System Kernel?

18) Difference between the fork(), exec() and system() . system calls?

19)How can you tell what shell you are running on UNIX system?

20)What is ‘the principle of locality’?What are conditions for a machine to support Demand Paging?

21)What are conditions on which deadlock can occur while swapping the processes?

22)What are the processes that are not bothered by the swapper? Give Reason.

23)How the Swapper works?

23)What do you mean by u-area (user area) or u-block?

24)What is a Region?

25)What scheme does the Kernel in Unix System V follow while choosing a swap device among the multiple swap devices?

26)What is the main goal of the Memory Management?

27)What is the difference between Swapping and ?

28)List the system calls used for process management?

29)How do you change File Access Permissions?

Refer the sites...
http://www.geekinterview.com/Interview-Questions/Operating-System/UNIX

Wednesday, 2 April 2008

UML

Unified Modeling Language?

Here I have tried to simplify the keyword UML.

In software engineering, whenever the pictorial graphical representation is required, as process document or some application architecture or design need to be elaborated, then it is done with the help of UML. Simply defining, the Unified Modeling Language (UML) is a standardized visual specification language for object modeling.

Defining in other terms , UML is a general-purpose modeling language that includes a graphical notation used to create an abstract model of a system, referred to as a UML model.

Going into bit detail description, UML is officially defined at the Object Management Group (OMG) by the UML metamodel, a Meta-Object Facility metamodel (MOF). Like other MOF-based specifications, the UML metamodel and UML models may be serialized in XML. UML was designed to specify, visualize, construct, and document software-intensive systems.

To understand more about the language, I have just framed and complied some general FAQ sort. I believe just going thru these answered questions, is enough to develop the basic understanding of the UML.

First of all, in the layman termed, basic query.

What is UML?
- Unified Modeling Language (UML) is the industry-standard language for specifying, visualizing, constructing, and documenting the artifacts of software systems. Using UML, programmers and application architects can make a blueprint of a project, which, in turn, makes the actual software development process easier.


What can I use UML for?
- UML was designed with these primary purposes in mind:
· Business process modeling with use cases
· Class and object modeling
· Component modeling
· Distribution and deployment modeling


What's the actual need of UML, isn't it enough to write some thing about our application's design and architecture, somewhere in documentation, without using the pictorial symbols of UML?
- While it's certainly possible to describe interrelated processes and code architecture in words, many people prefer to use a diagram to visualize the relationship of elements to one another. UML is a standard way to create these diagrams. As a result, it makes it easier for programmers and software architects to communicate.


Different types of diagrams available in UML?
- UML provides many different models of a system. The following is a list of then:
1) The Use Case Diagrams - A use case is a description of the system's behavior from a user's viewpoint.
2) The Class Diagrams - "What objects do we need? How will they be related?"
3) Collaboration Diagrams - "How will the objects interact?"
4) Sequence Diagrams - "How will the objects interact?"
5) State Diagrams - "What state should our object be in"
6) Package Diagrams - "How are we going to modularize our development?"
7) Component Diagrams - "How will our software components be related?"
8) Deployment Diagrams - "How will the software be deployed?"



What is a "use case"?
- A complete end-to-end business process that satisfies the needs of a user.


What are different categories of use cases?
- Detail Level: - High level / ExpandedTask Level: - Super / Sub (Abstract; Equal Alternatives; Complete v. Partial)Importance: - Primary / Secondary (use Secondary for exceptional processes)Abstraction: - Essential / Real


What is the difference between a real and essential use case?
- Essential - describes the "essence" of the problem; technology independent real - good for GUI designing; shows problem as related to technology decisions.


In a System Sequence Diagram, what is a System Event?
- It is from the expanded use case. It is an actor action the system directly responds to.


Give an example of a situation which a State Diagram could effectively model.
- Think of a cake and its different stages through the baking process: dough, baked, burned.


For what are Operations Contracts written?
- System Events.


In an Operations Contract's postconditions, four types of activities are specified. What are they?
- They are:
· Instances created
· Associations formed
· Associations broken
· Attributes changed



What does an Operations Contract do?
-Provides a snapshot of the System's state before and after a System Event. It is not interested in the Event's specific behavior.


What does a Collaboration Diagram (or Sequence Event, depending on the process) model?
- A System Event's behavior.


How does one model a class in a Collaboration Diagram? An instance?
- A box will represent both; however, a class is written as MyClass whereas an instance is written as myInstance:MyClass.


What are the three parts of a class in a Class Diagram?
- Name, Attributes, Methods.


In Analysis, we are interested in documenting concepts within the relevant problem domain. What is a concept?
- A person, place, thing, or idea that relates to the problem domain. They are candidates for objects.


Does a concept HAVE to become a class in Design?
- No.


In a Class Diagram, what does a line with an arrow from one class to another denote?
- Attribute visibility.


What are the four types of visibility between objects?

- Local
Parameter
Attribute
Global.


When do you use inheritance as opposed to aggregation?
- An aggregation is a "has a" relationship, and it is represented in the UML by a clear diamond.


When would I prefer to use composition rather than aggregation?
- Composition is a stronger form of aggregation. The object which is "contained" in another object is expected to live and die with the object which "contains" it. Composition is represented in the UML by a darkened diamond.

Is the UML a process, method, or notation?
- It is a notation. A process is Objectory, Booch, OMT, or the Unified Process. A process and a notation together make an OO method.



Friday, 28 March 2008

Design Patterns in OOPs

Introduction:


For starting with Design Patterns, pre-requiste is one should aware with the Object oriented concepts.

Here, we will try to simplify the term and purpose of the Design Pattern.

First normal and very common query could be, What is Design Patterns, why they are used?

In a simple layman term, a design pattern is a general reusable solution to a commonly occurring problem in software design.

Defining Design Patterns more descriptively...

In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern isn't a finished design that can be transformed directly into code.

It is a simply a description for how to solve a problem that can be used in many different situations.

Design patterns is used to speed up the development process by providing tested, proven development methods or paradigms. Effective software design requires considering issues that may not become visible until later in the implementation.

Reusing design patterns helps to prevent subtle issues that can cause major problems, and it also improves code readability for coders and architects who are familiar with the patterns.
Digging into depth,
Design Pattern is categoried in three different sub patterns.

Creational Patterns
Structural Patterns
Behavioral Patterns.


Creation Patterns
This design pattern is all about class instantiation.

This pattern can be further divided into class-creation patterns and object-creational patterns.

Abstract Factory : Creates an instance of several families of classes

Factory : Creates an instance of several derived classes
Builder : Separates object construction from its representation

Prototype : A fully initialized instance to be copied or cloned
Singleton : A class of which only a single instance can exist

Structural patterns

This design patterns is all about Class and Object composition. Structural class-creation patterns use inheritance to compose interfaces. Structural object-patterns define ways to compose objects to obtain new functionality.

Adaptor : Match interfaces of different classes
Bridge : Separates an object’s interface from its implementation
Decorator : Add responsibilities to objects dynamically
Facade : A single class that represents an entire subsystem
Proxy : An object representing another object

Behavioral patterns
This design patterns is all about Class's objects communication. Behavioral patterns are those patterns that are most specifically concerned with communication between objects.

Chain of responsibilty : A way of passing a request between a chain of objects
Command : Encapsulate a command request as an object
Interpreter : A way to include language elements in a program
Iterator : Sequentially access the elements of a collection
Observer : A way of notifying change to a number of classes
State : Alter an object's behavior when its state changes
Visitor : Defines a new operation to a class without change




Now we will pick the popular and commonly used design pattern and explain in detail.
Staring with the Factory Pattern.


What is a "factory" and why would you want to use one?
A factory, in this context, is a piece of software that implements one of the "factory" design patterns introduced . In general, a factory implementation is useful when you need one object to control the creation of and/or access to other objects. By using a factory in RMI, you can reduce the number of objects that you need to register with the RMI registry.

Examples of Factories in the Real World:
The Bank
The Library
These two example is sufficient to understand the actual process of the Factory Patterns. These examples are from the real life.

Let's take the example, commonly illustrated in the text book, GoF.
Widgets in a GUI Environment.
This example explains , how an Abstract Factory can be used to create widgets for a GUI environment. By designing the client to use the Abstract Factory interface, different factories can be created to generate different sets of widgets without requiring changes to the clients. This example is not intended to illustrate a useful implementation of Abstract Factory, as Java's AWT and Swing do the work for you, but it does show how easily design patterns can be implemented in RMI.
One other point to notice is how the pattern is split between client and server. This split was arbitrarily chosen, and with RMIs object-oriented nature you could decide to make the split in the pattern elsewhere.

In General , this pattern consists of two class hierarchies, one of Products, and one of Creators. Each ConcreteCreator class creates instances of specific ConcreteProduct classes using a factory method.

The factory pattern can help solve your application issues. For example, developers often must reply to users based on each user’s machine, creating multiple hardware issues. The factory pattern can streamline the process. The concept is simple, but the solutions created with the factory pattern are powerful.

For more understanding, let's take one more example.
Communications breakdown
Consider the example of a data collection application where various field devices supply data to the application via TCP/IP sockets. The application was originally written to communicate with one device but was expanded when the company produced a newer version. Unfortunately, this new hardware did not speak the same language as the previous version. Marketing required the application to support both hardware versions, since customers might buy new units and install them in tandem with older units. The factory pattern eased the burden of supporting multiple device types.

In short and effective explanation of fatory pattern is :
=> if we have a super class and n sub-classes, and based on data provided, we have to return the object of one of the sub-classes, we use a factory pattern.

Now, we will focus on the positive and negative points on using the Factory Patterns.
Positives:
-Eliminates the need to bind application-specific classes into your code
-Provides hooks for subclassing. Creating objects inside a class with a factory method is always more flexible than creating an object directly. This method gives subclasses a hook for providing an extended version of an object.
-Connects parallel heirarchies. Factory method localises knowledge of which classes belong together. Parallel class heirarchies result when a class delegates some of its responsibilities to a separate class.
Negatives:
-Clients might have to subclass the Creator class just to create a particular Concreate object.

>














Tuesday, 25 March 2008

Fear About US Recession.. Impact on Jobs


US market recession is almost declared, till now it was just a fear about the condition, by the time Mr. Warren Buffett admitted in his recent Interview and accepted about the chances of recession in US, and it could go even worst till ever happened.

Since US market is predominately considerable and play a major role all over the world' s economy, in all trades and businesses. So it's quite obvious to get scared from this situation.
Being an IT professional it's an obvious concern and worry to look into and know what is the scenario. To know, the fact and figures why are the people really scared about.

Curiously and sacredly I tried to compile the scenarios, which is I am sharing with . Most of the data I have taken the reference with nytimes.

The job market took a serious and unexpected turn for the worse in August, raising fears that the risks of a recession are greater than many economists had believed.

According to "The New York Times" , the economy shed 4,000 jobs between July and August, with industries that are connected to the housing market — like construction and manufacturing — making the deepest cuts, the Labor Department reported today. It was the first employment decline since 2003, when the job market was still struggling to emerge from a long slump in the wake of the 2001 recession.

The unemployment rate held steady at 4.6 percent in August, which economists said was likely a statistical fluke as more people stopped looking for work and were therefore not counted by the government as unemployed.

“If the economy is not headed toward recession, it is very close to one,” said Mark Zandi, chief economist in one of the .com site interview.

Stocks fell broadly and sharply, as investors digested the idea that the economy had been weakening significantly even before the mortgage crisis hit financial markets last month. The Dow Jones industrial average closed down almost 250 points, or 1.9 percent.
The jobs report all but guarantees that the Federal Reserve will cut its benchmark short-term interest rate when its policy-making committee meets on Sept. 18. A quarter-point reduction to 5 percent remains the most probable move, although a half-point cut now cannot be ruled out, economists said.

The weakness of the employment data seemed to change the terms of the debate over the health of the economy. The chances of a recession over the next year now seem to be somewhere between one-quarter and one-half, economists interviewed today said.
“I think at least people need to start thinking about the housing market not just as some ring fence problem which is off on its own, and the rest of the economy is doing just fine,” said Nigel Gault, chief United Economist with Global Insight, an economic research firm in Lexington, Mass. “They need to start worrying about the health of the broader economy.”

The Bush administration tried to defuse concerns that the weak jobs numbers hinted at a wider economic slowdown.

In an interview , the Treasury secretary, said the report was “not totally surprising.”
“There will be news that isn’t always good news,” he said. “But I feel quite strongly that we have a resilient economy.”


For months, Fed officials and Wall Street forecasters have been predicting that the housing slump would slow the economy, but that other strengths — like corporate earnings, growth in other countries and strong wage growth — would keep the slowdown from being severe. That could still happen; in both the 1980s and 1990s economic expansions, employment fell at least once before quickly reversing course.

“The financial turmoil and extended problems in housing put the risks for the economy clearly to the downside — no question,” said Mickey Levy, chief economist for
Bank of America. “But there are also factors that suggest a longer period of slower growth, but not recession.”

One of the most worrisome signs in the jobs report was the government’s revision to its employment data for June and July. The new numbers show just under 70,000 jobs created in each of the two months, down from an average of almost 110,000 according to its initial estimates.

In 2005 and 2006, the average monthly job growth was slightly above 200,000.
The sharp slowdown this year suggests that some employers have already begun to see a downturn in their business and others believe that one is on the way. With falling house prices in most of the country and rising oil prices, consumer spending has slowed modestly in recent months.

State and local government agencies, many of them dealing with budget shortfalls connected to the housing slump, have also cut an average of 27,000 jobs a month over the last three months. But economists said the declines in government employment, especially in schools, may have reflected seasonal quirks that made the job market look worse last month than it truly was.
Hospitals, doctors’ offices, restaurants and retailers all added jobs in August.

But the bright spots were few and far between. Employment in the finance sector — which includes real estate agencies and accounts for about 8.5 million of the country’s 138 million jobs — was flat in August, which could be a sign that the government numbers have not yet captured some of the mortgage-related job cuts now occurring.

The surveys that made up the Labor Department report measured employment from Aug. 12 to Aug. 18, when the credit squeeze and subsequent stock market turmoil were under way but not fully felt. Since then, some large lenders like Countrywide and
Lehman Brothers have continued to lay off workers. And just today, IndyMac Bancorp, a large mortgage lender, said it would be cutting about 1,000 jobs over the next several months.

“There probably was not that much influence in the data from the credit shock,” said Richard Berner, chief United States economist at
Morgan Stanley. “So I think more weakness in the economy is likely. The economy is clearly losing momentum.”

The extent to which the economy continues to lose momentum will determine the Fed’s course of action. The price of a futures contract tied to Fed policy shows that the central bank will probably cut the benchmark rate, now at 5.25 percent, to 4.5 percent by the end of the year. But a growing number of economists are saying that might not be soon enough.

Mr. Gault of Global Insight, who is forecasting a half-point cut on Sept. 18, said it would send “an important message that the Fed sees there are real problems here, there’s a real threat, and it needs to have a response that’s commensurate to that threat.”

Although the unemployment rate held steady at 4.6 percent, the percentage of adults with jobs fell to 62.8 percent, from 63 percent in July and a peak of 63.4 percent in December. The number of people who were neither working nor looking for work — and thus considered neither employed nor unemployed by the government — rose by almost 600,000 in August.

“That’s a sign of economic weakness,” Mr. Anderson, of
Wells Fargo, said. “Perhaps people just gave up trying to find jobs.”
The number of people with part-time jobs who said they would prefer to full time has also been rising in recent months. In August, the Labor Department classified 4.5 million workers as “part time for economic reasons,” up from 4.3 million in July.

Wage growth, which often lags behind job growth, did continue at roughly its recent pace. Average hourly earnings for rank-and-file workers — who make up about four-fifths of the work force — have increased 3.9 percent over the last year, to $17.50. Inflation has been running at about 2.5 percent a year.

Wall Street had eagerly awaited the jobs report because it was the most significant economic data released since financial markets began to tumble in early August. If the jobs report had been merely lackluster, it might have been welcomed by investors as a sign that a Fed rate cut all but certain and the economy was still growing at a healthy pace.

The reversal in job growth, however, was far different from the gain of roughly 100,000 jobs that Wall Street was expecting, raising worries that corporate profits will weaken as the market upheaval moves beyond the housing and financial sectors.
<<All these data, statistics and above figure stats, I have complied through internet sites and other sources.>>

Friday, 21 March 2008

DON'T CHALLENGE MECHANICAL FOR IT...


General Motors REPLY TO BILL GATES...

At a recent computer expo (COMDEX), Bill Gates reportedly compared the computer industry with the auto industry and stated, "If GM had kept up with technology like the computer industry has, we would all be driving $25.00 cars that got 1,000 miles to the gallon."

In response to Bill's comments, General Motors issued a press release Stating:

"If GM had developed technology like microsoft, we would all be driving cars with the following characteristics (and I just love this part, esp 7th point and 10'th point):

1. For no reason whatsoever, your car would crash twice a day.

2. Every time they repainted the lines in the road, you would have to buy a new car.

3. Occasionally your car would die on the freeway for no reason. You would have to pull to the side of the road, close all of the windows, shut off the car, restart it, and reopen the windows before you could continue. For some reason you would simply accept this.

4. Occasionally, executing a maneuver such as a left turn would cause your car to shut down and refuse to restart, in which case you would have to reinstall the engine.

5. Macintosh would make a car that was powered by the sun, was reliable, five times as fast and twice as easy to drive - but would ! run on only five percent of the roads.

6. The oil, water temperature, and alternator warning lights would all be replaced by a single "This Car Has Performed an Illegal Operation" warning light.

7. The airbag system would ask "Are you sure?" before deploying.

8. Occasionally, for no reason whatsoever, your car would lock you out and refuse to let you in until you simultaneously lifted the door handle, turned the key and grabbed hold of the radio antenna. (Read CTR-ALT-DEL)

9. Every time a new car was introduced car buyers would have to learn how to drive all over again because none of the controls would operate in the same manner as the old car.

10. You'd have to press the "Start" button to turn the engine off. "

Are you Serial Killer!!!

Test your self...

A woman, while at the funeral of her own mother, met a guy whom she did not know. She thought this guy was amazing.

She believed him to be her dream guy so much, that she fell in love with him right there, but never asked for his number and could not find him.
A few days later she killed her sister.

Question: What is her motive for killing her sister?