Java classpath usage

Posted on 20 Kasım 2016 in Programlama by

We will create following classes:

Create a class with package name as p1.p2.p3 at firstClass directory

package p1.p2.p3;
public class abc {
    public void printName(String name) {
        System.out.println("your name is "+name);

and compile it using following command:
javac -d .

lets add another class that uses abc class at secondClass directory

public class xyz extends{
    public static void main(String prm[]) {
        System.out.println("xyz class");
        tt deneme = new tt();

and following command is used to compile it:
javac -classpath ../firstClass/

To execute compiled binary use following command:
java -cp .:../firstClass xyz

callgraph generator

Posted on 14 Temmuz 2016 in Programlama by

sudo apt-get install -y kcachegrind valgrind
gcc main.c
valgrind --tool=callgrind ./a.out
# Generates a callgrind.out.<PID> file.
kcachegrind callgrind.out.1234
# Opens a GUI to visualize callgrind data.

auto_ptr and reference counting

Posted on 16 Ekim 2015 in Programlama by


A smart pointer is a class that wraps a ‘raw’ (or ‘bare’) C++ pointer, to manage the lifetime of the object being pointed to. There is no single smart pointer type, but all of them try to abstract a raw pointer in a practical way.

Smart pointers should be preferred over raw pointers. If you feel you need to use pointers (first consider if you really do), you would normally want to use a smart pointer as this can alleviate many of the problems with raw pointers, mainly forgetting to delete the object and leaking memory.

With raw pointers, the programmer has to explicitly destroy the object when it is no longer useful.

// Need to create the object to achieve some goal
MyObject* ptr = new MyObject(); 
ptr->DoSomething(); // Use the object in some way
delete ptr; // Destroy the object. Done with it.
// Wait, what if DoSomething() raises an exception...?

A smart pointer by comparison defines a policy as to when the object is destroyed. You still have to create the object, but you no longer have to worry about destroying it.

SomeSmartPtr<MyObject> ptr(new MyObject());
ptr->DoSomething(); // Use the object in some way.

// Destruction of the object happens, depending 
// on the policy the smart pointer class uses.

// Destruction would happen even if DoSomething() 
// raises an exception

The simplest policy in use involves the scope of the smart pointer wrapper object, such as implemented by boost::scoped_ptr or std::unique_ptr.

void f()
       boost::scoped_ptr<MyObject> ptr(new MyObject());
    } // boost::scopted_ptr goes out of scope -- 
      // the MyObject is automatically destroyed.

    // ptr->Oops(); // Compile error: "ptr" not defined
                    // since it is no longer in scope.

Note that scoped_ptr instances cannot be copied. This prevents the pointer from being deleted multiple times (incorrectly). You can, however, pass references to it around to other functions you call.

Scoped pointers are useful when you want to tie the lifetime of the object to a particular block of code, or if you embedded it as member data inside another object, the lifetime of that other object. The object exists until the containing block of code is exited, or until the containing object is itself destroyed.

A more complex smart pointer policy involves reference counting the pointer. This does allow the pointer to be copied. When the last “reference” to the object is destroyed, the object is deleted. This policy is implemented by boost::shared_ptr and std::shared_ptr.

void f()
    typedef std::shared_ptr<MyObject> MyObjectPtr; // nice short alias
    MyObjectPtr p1; // Empty

        MyObjectPtr p2(new MyObject());
        // There is now one "reference" to the created object
        p1 = p2; // Copy the pointer.
        // There are now two references to the object.
    } // p2 is destroyed, leaving one reference to the object.
} // p1 is destroyed, leaving a reference count of zero. 
  // The object is deleted.

Reference counted pointers are very useful when the lifetime of your object is much more complicated, and is not tied directly to a particular section of code or to another object.

There is one drawback to reference counted pointers — the possibility of creating a dangling reference:

// Create the smart pointer on the heap
MyObjectPtr* pp = new MyObjectPtr(new MyObject())
// Hmm, we forgot to destroy the smart pointer,
// because of that, the object is never destroyed!

Another possibility is creating circular references:

struct Owner {
   boost::shared_ptr<Owner> other;

boost::shared_ptr<Owner> p1 (new Owner());
boost::shared_ptr<Owner> p2 (new Owner());
p1->other = p2; // p1 references p2
p2->other = p1; // p2 references p1

// Oops, the reference count of of p1 and p2 never goes to zero!
// The objects are never destroyed!

To work around this problem, both Boost and C++11 have defined a weak_ptr to define a weak (uncounted) reference to a shared_ptr.

This answer is rather old, and so describes what was ‘good’ at the time, which was smart pointers provided by the Boost library. Since C++11, the standard library has provided sufficient smart pointers types, and so you should favour the use of std::unique_ptr, std::shared_ptr and std::weak_ptr.

There is also std::auto_ptr. It is very much like a scoped pointer, except that it also has the “special” dangerous ability to be copied — which also unexpectedly transfers ownership! It is deprecated in the newest standards, so you shouldn’t use it.

std::auto_ptr<MyObject> p1 (new MyObject());
std::auto_ptr<MyObject> p2 = p1; // Copy and transfer ownership. 
                                 // p1 gets set to empty!
p2->DoSomething(); // Works.
p1->DoSomething(); // Oh oh. Hopefully raises some NULL pointer exception.

How to inter process communication

Posted on 14 Ekim 2015 in Programlama by

File A record stored on disk, or a record synthesized on demand by a file server, which can be accessed by multiple processes. Most operating systems
Signal A system message sent from one process to another, not usually used to transfer data but instead used to remotely command the partnered process. Most operating systems
Socket A data stream sent over a network interface, either to a different process on the same computer or to another computer on the network. Most operating systems
Message queue An anonymous data stream similar to a socket, usually implemented by the operating system, that allows multiple processes to read and write to the message queue without being directly connected to each other. Most operating systems
Pipe A two-way data stream between two processes interfaced through standard input and output and read in one character at a time. All POSIX systems, Windows
Named pipe A pipe implemented through a file on the file system instead of standard input and output. Multiple processes can read and write to the file as a buffer for IPC data. All POSIX systems, Windows
Semaphore A simple structure that synchronizes multiple processes acting on shared resources. All POSIX systems, Windows
Shared memory Multiple processes are given access to the same block of memory which creates a shared buffer for the processes to communicate with each other. All POSIX systems, Windows
Message passing Allows multiple programs to communicate using channels, commonly used in concurrency models. Used in MPI paradigm, Java RMICORBADDSMSMQMailSlotsQNX, others
Memory-mapped file A file mapped to RAM and can be modified by changing memory addresses directly instead of outputting to a stream. This shares the same benefits as a standard file. All POSIX systems, Windows

Start a Simple HTTP Server in Any Folder

Posted on 05 Ekim 2015 in Programlama by

The number at the end is the port to use, open your browser and visit http://localhost:8000 You can use the default of port 80 if you wish and remove the port number entirely.

When you’re finished, simply press Ctrl-C.

Macs instantly maximize windows

Posted on 05 Ekim 2015 in İnternet, Programlama by

To speed up execute following command:

defaults write -g NSWindowResizeTime -float 0.003

Quit and relaunch all apps for the change to take effect, including Finder

To undo:

defaults delete -g NSWindowResizeTime

Some others:

# opening and closing windows and popovers
defaults write -g NSAutomaticWindowAnimationsEnabled -bool false

# smooth scrolling
defaults write -g NSScrollAnimationEnabled -bool false

# showing and hiding sheets, resizing preference windows, zooming windows
# float 0 doesn't work
defaults write -g NSWindowResizeTime -float 0.001

# opening and closing Quick Look windows
defaults write -g QLPanelAnimationDuration -float 0

# rubberband scrolling (doesn't affect web views)
defaults write -g NSScrollViewRubberbanding -bool false

# resizing windows before and after showing the version browser
# also disabled by NSWindowResizeTime -float 0.001
defaults write -g NSDocumentRevisionsWindowTransformAnimation -bool false

# showing a toolbar or menu bar in full screen
defaults write -g NSToolbarFullScreenAnimationDuration -float 0

# scrolling column views
defaults write -g NSBrowserColumnAnimationSpeedMultiplier -float 0

# showing the Dock
defaults write autohide-time-modifier -float 0
defaults write autohide-delay -float 0

# showing and hiding Mission Control, command+numbers
defaults write expose-animation-duration -float 0

# showing and hiding Launchpad
defaults write springboard-show-duration -float 0
defaults write springboard-hide-duration -float 0

# changing pages in Launchpad
defaults write springboard-page-duration -float 0

# at least AnimateInfoPanes
defaults write DisableAllAnimations -bool true

# sending messages and opening windows for replies
defaults write DisableSendAnimations -bool true
defaults write DisableReplyAnimations -bool true

Again to undo:
defaults write -g NSAutomaticWindowAnimationsEnabled -bool false
defaults write -g NSScrollAnimationEnabled -bool false
defaults write -g NSWindowResizeTime -float 0.001
defaults write -g QLPanelAnimationDuration -float 0
defaults write -g NSScrollViewRubberbanding -bool false
defaults write -g NSDocumentRevisionsWindowTransformAnimation -bool false
defaults write -g NSToolbarFullScreenAnimationDuration -float 0
defaults write -g NSBrowserColumnAnimationSpeedMultiplier -float 0
defaults write autohide-time-modifier -float 0
defaults write autohide-delay -float 0
defaults write expose-animation-duration -float 0
defaults write springboard-show-duration -float 0
defaults write springboard-hide-duration -float 0
defaults write springboard-page-duration -float 0
defaults write DisableAllAnimations -bool true
defaults write DisableSendAnimations -bool true
defaults write DisableReplyAnimations -bool true

To undo the changes, paste this into the terminal:

defaults delete -g NSAutomaticWindowAnimationsEnabled
defaults delete -g NSScrollAnimationEnabled
defaults delete -g NSWindowResizeTime
defaults delete -g QLPanelAnimationDuration
defaults delete -g NSScrollViewRubberbanding
defaults delete -g NSDocumentRevisionsWindowTransformAnimation
defaults delete -g NSToolbarFullScreenAnimationDuration
defaults delete -g NSBrowserColumnAnimationSpeedMultiplier
defaults delete autohide-time-modifier
defaults delete autohide-delay
defaults delete expose-animation-duration
defaults delete springboard-show-duration
defaults delete springboard-hide-duration
defaults delete springboard-page-duration
defaults delete DisableAllAnimations
defaults delete DisableSendAnimations
defaults delete DisableReplyAnimations

Mac OS X also has dialog boxes, such as the ‘Save As’-box (CMD+SHIFT+S) or the ‘Print’-box (CMD+P). You can tweak the speed at which all of these boxes appear by using these commands:


defaults write NSGlobalDomain NSWindowResizeTime .001


defaults write NSGlobalDomain NSWindowResizeTime .1

Default (0.2 seconds):

defaults delete NSGlobalDomain NSWindowResizeTime

1 = 1 second. To see the difference you have to re-launch an app such as Terminal and summon a dialog box by pressing CMD+S (‘Save’) for example. You can find more command-line tweaks in


DTD tutorial for xml

Posted on 02 Ekim 2015 in Programlama by

You can find a good dtd tutorial at following page:

Loading libraries with LD_LIBRARY_PATH

Posted on 26 Ağustos 2015 in Programlama by

You can create any config file under following path:


then run:

ldconfig -v

With those steps no need to call:
export LD_LIBRARY_PATH=/usr/local/lib

Basic multiprocess server design in c

Posted on 24 Ağustos 2015 in Programlama by

Following code creates a new subprocess per connection from the port 1005. You can show them all by ps command.


                          main.c  -  description
    begin                : Thu Jun  1 20:30:59 IST 2006
    copyright            : (C) |YEAR| by Am2006a
    email                :

 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *

#include <config.h>

#include <stdio.h>
#include <stdlib.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define PORT 1005   // port we're listening on

int main(void)
    struct sockaddr_in myaddr;     // server address
    struct sockaddr_in remoteaddr; // client address
    int fdmax;        // maximum file descriptor number
    int listener;     // listening socket descriptor
    int newfd,pid;        // newly accept()ed socket descriptor
    char buf[256];    // buffer for client data
    int nbytes;
    int yes=1;        // for setsockopt() SO_REUSEADDR, below
    socklen_t addrlen;
    int i, j,b_status,c=0;
	char ch[20];
    // get the listener
    if ((listener = socket(AF_INET, SOCK_STREAM, 0)) == -1) {

    // lose the pesky "address already in use" error message
    if (setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {

    // bind
    myaddr.sin_family = AF_INET;
    myaddr.sin_addr.s_addr = ntohl(INADDR_LOOPBACK);
    myaddr.sin_port = htons(PORT);
    memset(&(myaddr.sin_zero), '\0', 8);
    if (bind(listener, (struct sockaddr *)&myaddr, sizeof(myaddr)) == -1) {

    // listen
    if (listen(listener, 10) == -1) {
    printf("Server Started.Listening for incoming connections\n\n");
    while(1) {
        if ((newfd = accept(listener, (struct sockaddr *)&remoteaddr,&addrlen)) == -1) {
            // fork a new child whenever we have a new client connection
                //handle the client
                printf("new connection from %s on socket %d\n", inet_ntoa(remoteaddr.sin_addr),newfd);
                printf("Recieved %d bytes from the client",read(newfd,buf,sizeof(buf)));

                //do any other tasks as needed
    return 0;

Recursive Makefile Example

Posted on 20 Ağustos 2015 in Programlama by

I wanted to come up with generic way using only make (no autoconf/automake/etc) to solve the following problem:

Given a source directory with several subdirectories, have it so that running make in the top directory runs the make in all the subdirectories, potentially with dependencies so that things are built in the correct order. This should work for “make”, “make install”, “make clean”, etc.

The make manual has a good description of this (in the “Phony targets” section of all places. It says

Another example of the usefulness of phony targets is in conjunction with recursive invocations of make (for more information, see Recursive Use of make). In this case the makefile will often contain a variable which lists a number of subdirectories to be built. One way to handle this is with one rule whose command is a shell loop over the subdirectories, like this:

     SUBDIRS = foo bar baz
             for dir in $(SUBDIRS); do \
               $(MAKE) -C $$dir; \

There are a few problems with this method, however. First, any error detected in a submake is not noted by this rule, so it will continue to build the rest of the directories even when one fails. This can be overcome by adding shell commands to note the error and exit, but then it will do so even if make is invoked with the -k option, which is unfortunate. Second, and perhaps more importantly, you cannot take advantage of make’s ability to build targets in parallel (see Parallel Execution), since there is only one rule.

By declaring the subdirectories as phony targets (you must do this as the subdirectory obviously always exists; otherwise it won’t be built) you can remove these problems:

     SUBDIRS = foo bar baz
     .PHONY: subdirs $(SUBDIRS)
     subdirs: $(SUBDIRS)
             $(MAKE) -C $@
     foo: baz

Here we’ve also declared that the foo subdirectory cannot be built until after the baz subdirectory is complete; this kind of relationship declaration is particularly important when attempting parallel builds.

The point about not using loops and instead making the subdirs themselves targets seems like a good idea and works for our “make” case. Well what about “make install”? We’re already using the subdir names as targets for the normal “make”, so we can’t do the same trick exactly, but we can invent new target names

INSTALLDIRS = $(SUBDIRS:%=install-%)

install: $(INSTALLDIRS)
	$(MAKE) -C $(@:install-%=%) install

.PHONY: install

In the first line, for each directory in SUBDIRS, we create a corresponding list of directories with “install-” prefixed (but could just as easily be a list of dirs). Next we have an install target that depends on all of them, and then we have a generic target that for each of them determines the the subdir name (by stripping off the “install-“) and does a “make install” in that directory. Last we declare these made up targets as phony.

OK, so can we use this technique for other targets too? Sure, and while we’re at it lets make our original solution for “make” use “build-” as a prefix for consistency (we are using .PHONY for all these targets, but it’s probably a good idea to have the target names not correspond to any real file/dir).

So here’s the end result, a sample Makefile for a ficticious project that has a few directories and some dependencies along with some other good ideas suggested by the GNU Coding Standards.

# example Makefile
SHELL = /bin/sh
INSTALL = /usr/bin/install
include Makefile.conf

DIRS = dev ui utils doc
# the sets of directories to do various things in
BUILDDIRS = $(DIRS:%=build-%)
INSTALLDIRS = $(DIRS:%=install-%)
CLEANDIRS = $(DIRS:%=clean-%)
TESTDIRS = $(DIRS:%=test-%)

	$(MAKE) -C $(@:build-%=%)

# the utils need the libraries in dev built first
build-utils: build-dev

install: $(INSTALLDIRS) all
	$(MAKE) -C $(@:install-%=%) install

test: $(TESTDIRS) all
	$(MAKE) -C $(@:test-%=%) test

clean: $(CLEANDIRS)
	$(MAKE) -C $(@:clean-%=%) clean

.PHONY: subdirs $(DIRS)
.PHONY: subdirs $(BUILDDIRS)
.PHONY: subdirs $(TESTDIRS)
.PHONY: subdirs $(CLEANDIRS)
.PHONY: all install clean test

** This article is copied from