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                : amitsaha.in@gmail.com

 *                                                                         *
 *   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 http://lackof.org/taggart/hacking/make-example

Posix thread notes

Posted on 19 Ağustos 2015 in Programlama by

pthread_once example



Save following code as main.c and compile with the given command.

#include <stdio.h>
#include <pthread.h>

pthread_once_t once_control = PTHREAD_ONCE_INIT;

void library_init( void )
    printf ("pthread once\n");

void * library_entry_point1(void *p1)
    pthread_once( &once_control, library_init );

void * library_entry_point2(void *p2)
    pthread_once( &once_control, library_init );

int main ()
	pthread_t t1, t2;
	pthread_create(&t1, NULL, library_entry_point1, (void*)NULL);
	pthread_create(&t2, NULL, library_entry_point2, (void*)NULL);
	pthread_join(t1, NULL);
	pthread_join(t2, NULL);
	return 0;

compile as gcc main.c -o main -lpthread

Difference between pthread_rwlock_wrlock and pthread_mutex_lock

The pthread_mutex_lock is a general purpose lock object. The
locking thread causes all other threads that use that mutex to block.
Very simple. The pthread_rwlock_wrlock() and its sibling
pthread_rwlock_rdlock() implement a reader-writer strategy there are
many readers and a few writers. The basic issue is that you want to
allow reader threads to proceed, but you want to block writers. If a
writer thread calls pthread_rwlock_wrlock(), it will block if a reader
thread has called the rdlock, but it will also block subsequent
readers. So basically, in your question, if you only use wrlock() then
the effect is the same as the standard mutex lock, but it appears
there is more overhead associated with it.

NM command and symbol meanings

Posted on 14 Ağustos 2015 in Programlama by

 * File name: test.c
 * For C code compile with: 
 * gcc -c test.c
 * For C++ code compile with:
 * g++ -c test.cpp

int global_var;
int global_var_init = 26;

static int static_var;
static int static_var_init = 25;

static int static_function()
	return 0;

int global_function(int p)
	static int local_static_var;
	static int local_static_var_init=5;

	local_static_var = p;

	return local_static_var_init + local_static_var;

int global_function2()
	int x;
	int y;
	return x+y;

#ifdef __cplusplus
extern "C"
void non_mangled_function()
	// I do nothing

int main(void)
	global_var = 1;
	static_var = 2;

	return 0;

If the previous code is compiled with the gcc C compiler, the output of the nm command is the following:

# nm test.o
0000000a T global_function
00000025 T global_function2
00000004 C global_var
00000000 D global_var_init
00000004 b local_static_var.1255
00000008 d local_static_var_init.1256
0000003b T main
00000036 T non_mangled_function
00000000 t static_function
00000000 b static_var
00000004 d static_var_init

When the C++ compiler is used, the output differs:

# nm test.o
0000000a T _Z15global_functioni
00000025 T _Z16global_function2v
00000004 b _ZL10static_var
00000000 t _ZL15static_functionv
00000004 d _ZL15static_var_init
00000008 b _ZZ15global_functioniE16local_static_var
00000008 d _ZZ15global_functioniE21local_static_var_init
U __gxx_personality_v0
00000000 B global_var
00000000 D global_var_init
0000003b T main
00000036 T non_mangled_function

The differences between the outputs also show an example of solving the name mangling problem by using extern “C” in C++ code.

Posted on 29 Temmuz 2015 in Fotoğrafçılık by

Photo of the day (meerkats)

Launching application with keyboard shortcut in linux (centos, fedora, redhat)

Posted on 04 Temmuz 2015 in Programlama by

Settings > Keyboard > Shortcuts > Custom Shortcuts

Click the + button.





Click the Add button.

Now click on the text saying disabled and enter your custom shortcut, i.e. Ctrl-Alt-T.

Heap sort

Posted on 27 Haziran 2015 in Programlama by

Wikipedia has a good tutorial for heap tree.


Following implementation is copied from the page:



What is a Max Heap ?

Max heap is data structure that satisfies two properties :

Shape property

It states that max heap is a complete binary tree, which is a binary tree that is filled at all levels, except perhaps the last level, which is filled from left to right.

We can infer a couple of things from the above statement. Firstly, the leaf nodes of the tree will be in last level or the level above it. Secondly, in all levels except perhaps the last level, every parent node should exactly have two children. And finally, no right sibilng can exist without its left sibling.

Heap property

It states that the value of the parent node is always greater than or equal to that of its children.

It means that the maximum value in the heap shall occur at the root node, and the minimum value in the heap shall occur at any of the leaf nodes. Do note that heap property doesn’t mention any relationship between the left and right sibling of a node. The left sibling may have a value greater than the right sibling, or it may be the other way around. As long as every parent has a value greater than its siblings, heap property is satisifed.

If any of the above two property is violated, its not a max heap.

Various Heap Operations

Various operations like insertion and deletion of a node can be done efficiently using a max heap structure. But before we get into that, lets first start with how to create a max heap structure. Given below is the C code for the same.

#define LCHILD(x) 2 * x + 1
#define RCHILD(x) 2 * x + 2
#define PARENT(x) x / 2

typedef struct node {
    int data ;
} node ;

typedef struct maxHeap {
    int size ;
    node *elem ;
} maxHeap ;

In the above code, we are creating two structures, one to represent a node and other to represent the entire max heap. The node structure has only a single member to hold the data. The maxHeap structure has two members – one to hold the total size of the max heap at any time, and the other is a pointer to the heap.

Though the heap can be implemented using various child and parent pointers, its easier to use a dynamic array. Since in C array indexing begins at index 0, given a node at index i, its left child shall be at (2 * i + 1) and right child shall be at (2 * i + 2). Also, given a node at index i, its parent node shall be at index x / 2.

Since the max heap can be growing dynamically, we shall be using a dynamic array which shall grow and shrink its size as required.

We also need an initializor function that shall initialize the data members of the max heap with default values.

maxHeap initMaxHeap(int size) {
    maxHeap hp ;
    hp.size = 0 ;
    return hp ;

We are creating a variale of type maxHeap and setting its size variable to 0, and returning the maxHeap variable back. So in the main function, you can have something like,

maxHeap hp = initMaxHeap() ;


At best case, it takes only O(1) time to insert a node into max heap. But at worst case, the new node may be greater than all nodes in the heap, that it needs to be compared with log(n) elements at most to be put into the root node position. So insertion operation is normally considered as an O(logn) operation. Given below is the C code for the same.

void insertNode(maxHeap *hp, int data) {
    // allocating space
    if(hp->size) {
        hp->elem = realloc(hp->elem, (size + 1) * sizeof(node)) ;
    } else {
        hp->elem = malloc(sizeof(node)) ;

    // initializing the node with value
    node nd ;
    nd.data = data ;

    // Positioning the node at the right position in the max heap
    int i = (hp->size)++ ;
    while(i && nd.data > hp->elem[PARENT(i)].data) {
        hp->elem[i] = hp->elem[PARENT(i)] ;
        i = PARENT(i) ;
    hp->elem[i] = nd ;

In first part of insertNode() function, we allocate space for one node. On its first iteration, size variable is zero, and hence call to malloc() function is performed. Henceforth, all calls shall go to realloc() function which shall increase the memory to allocate one more node in the max heap.

In second part of insertNode() function, we simply create a node variable and initialize it with data that we need to store in the node.

In last part of insertNode() function, we shall find the correct position for the new node in max heap structure. We consider the new memory space created. We shall compare value of last node with the new node value. If its less, we shall move it to the new memory location. We shall now check its parent node, and compare it with new node. If its less, we shall move it to old position of last node. It will continue until we find a node which has value higher than the new node, and place the new node as a child node of that node.


Deletion operation is quite different from insertion operation. In each deletion operation, we shall delete the maximum element from max heap, ie, we shall always delete the root node in each deletion operation, and place the last node in root node position. Since we are placing a leaf node in root node, its guaranteed that heap property shall be violated. We shall then call a special function called heapify() function recursively to make sure that heap property is satisfied.

void swap(node *n1, node *n2) {
    node temp = *n1 ;
    *n1 = *n2 ;
    *n2 = temp ;
void heapify(maxHeap *hp, int i) {
    int largest = (LCHILD(i) < hp->size && hp->elem[LCHILD(i)].data > hp->elem[i].data) ? LCHILD(i) : i ;
    if(RCHILD(i) < hp->size && hp->elem[RCHILD(i)].data > hp->elem[largest].data) {
        largest = RCHILD(i) ;
    if(largest != i) {
        swap(&(hp->elem[i]), &(hp->elem[largest])) ;
        heapify(hp, largest) ;
void deleteNode(maxHeap *hp) {
    if(hp->size) {
        printf("Deleting node %d\n\n", hp->elem[0].data) ;
        hp->elem[0] = hp->elem[--(hp->size)] ;
        hp->elem = realloc(hp->elem, hp->size * sizeof(node)) ;
        heapify(hp, 0) ;
    } else {
        printf("\nMax Heap is empty!\n") ;
        free(hp->elem) ;

In deleteNode() function, last node is placed at root node position, heap size decremented by 1, and memory of max heap reduced by one node. Heapify() function shall then be called.

In heapify() function, given a node at index i, we shall compare all the three nodes (parent, left and right child), and find the largest node of the three. If its not the parent node, then heap property is violated. Swap parent node with largest node, and call heapify() function until heap property is satisfied.


Given an array of n numbers, we can call the insertNode() function n times to create the max heap. Since each call to insertNode() can take upto O(logn) time, we need a maximum of O(nlogn) time to create the entire max heap. But instead of following such an approach, we can follow a relatively better buildMaxHeap() function that requires only O(n) time.

void buildMaxHeap(maxHeap *hp, int *arr, int size) {
    int i ;

    // Insertion into the heap without violating the shape property
    for(i = 0; i < size; i++) {
        if(hp->size) {
            hp->elem = realloc(hp->elem, (hp->size + 1) * sizeof(node)) ;
        } else {
            hp->elem = malloc(sizeof(node)) ;
        node nd ;
        nd.data = arr[i] ;
        hp->elem[(hp->size)++] = nd ;

    // Making sure that heap property is also satisfied
    for(i = (hp->size - 1) / 2; i >= 0; i--) {
        heapify(hp, i) ;

In first step, we insert all elements from the array into the max heap without bothering about heap property. Since the heap is built using array structure, shape property is never violated.

In last step, we shall determine the last parent in the heap and call heapify() function on that parent node, until heap property is satisfied for that node. We shall then work back by calling heapify() function on each of those parent nodes, until we reach root node, by which time, heap property shall be satisfied.


There are mainly two types of traversals possible on a max heap – depth first traversal and breadth first (level order) traversal.

In depth first traversal, we visit the nodes depth-wise, meaning that we go deeper and deeper into childrens of a left sibling before covering the right sibling. There are mainly three depth first traversals possible – inorder, preorder and postorder traversal.

Inorder Traversal

void inorderTraversal(maxHeap *hp, int i) {
    if(LCHILD(i) < hp->size) {
        inorderTraversal(hp, LCHILD(i)) ;
    printf("%d ", hp->elem[i].data) ;
    if(RCHILD(i) < hp->size) {
        inorderTraversal(hp, RCHILD(i)) ;

In the above function, we check whether left child of a node at index i exists in the heap. If yes, we call the inorderTraveral() function on the left child. We now display value of the node at index i. Then we check whether right child of a node at index i exists in the heap. If yes, we call inorderTraversal() on the right child. This shall continue until we traverse the whole max heap.

Preorder Traversal

void preorderTraversal(maxHeap *hp, int i) {
    if(LCHILD(i) < hp->size) {
        preorderTraversal(hp, LCHILD(i)) ;
    if(RCHILD(i) < hp->size) {
        preorderTraversal(hp, RCHILD(i)) ;
    printf("%d ", hp->elem[i].data) ;

In the above function, we check whether left child of the node at index i exists. If yes, we call preorderTraversal() on the left child. We then check whether right of the node exists. If yes, we call preorderTraversal() on the right child. we then display the value of the node at index i. We can see that code for preorderTraversal() and inorderTraversal() are quite similar and shall be similar to postorderTraversal() function. The only difference is the order in which the recursive functions are called.

Postorder Traversal

void postorderTraversal(maxHeap *hp, int i) {
    printf("%d ", hp->elem[i].data) ;
    if(LCHILD(i) < hp->size) {
        postOrderTraversal(hp, LCHILD(i)) ;
    if(RCHILD(i) < hp->size) {
        postorderTraversal(hp, RCHILD(i)) ;

In postOrderTraversal() function, we display the value of the node at index 1, and recursively call the function, first on the left child and then on the right child, until we traverse the whole max heap.

Levelorder Traversal

void levelOrderTraversal(maxHeap *hp) {
    int i ;
    for(i = 0; i < hp->size; i++) {
        printf("%d ", hp->elem[i].data) ;

Implementing level order traversal is quite simple, as we are using the array implementation. All we need to do is to traverse through the whole array from index 0 to (hp->size – 1) to get the level order traversal.

Applications of Max Heap

As you are already aware by now, when we delete an element from the max heap, we always get the maximum valued node from the max heap, which means that we can access the maximum valued node in O(1) time. So if you need a quick access to the largest value element, you can go for max heap implementation.

Max heaps can be used to implement priority queues. In a priority queue, rather than using the value of a node, we are using priority of the node to position it in the max heap. Priority queues are used heavily in job schedulers.

Ldap apache directory studio tutorial

Posted on 18 Mayıs 2015 in Programlama by

p4-ldapYou can find a good tutorial here and content is copied from the following page:


Continue reading…