Tuesday, December 29, 2009

Erlang Parsing Example

%% Erlang Program to Parse a list/string
%% Date : 19-Aug-2009
%% Author: Prakhar Dubey :prakharprakhar@gmail.com
%% Program shows the use of string:tokens, list iterator and
%% fun callback function.

-module(parse).
-export([init/0]).

init() ->
Str = "tool.,www.tool.com.,2081991958,34!tool.,www.tool.com.,2081991958,34!tool.,www.tool.com.,2081991958,34!tool.,www.tool.com.,2081991958,34!tool.,www.tool.com.,2081991958,34!tool.,www.tool.com.,2081991958,34!tool.,www.tool.com.,2081991958,34!tool.,www.tool.com.,2081991958,34!tool.,www.tool.com.,2081991958,34!tool.,www.tool.com.,2081991958,34!tool.,www.tool.com.,2081991958,34!tool.,www.tool.com.,2081991958,34!tool.,www.tool.com.,2081991958,34!tool.,www.tool.com.,2081991958,34!tool.,www.tool.com.,2081991958,34!tool.,www.tool.com.,2081991958,34!sun.com.,www.starplus.com.,3252467389,39!",

B = string:tokens(Str,"!"),

Print = fun(L) -> io:format("Values:~p~n",[L]) end,

Callback = fun(E) -> C = string:tokens(E,","),lists:foreach(Print,C), io:format("Element:~p~n",[E]) end,

lists:foreach(Callback,B),
ok.

Monday, December 28, 2009

Creating Libraries

The following are more examples of all three approaches (static, shared, and dynamically loaded libraries). File libhello.c is a trivial library, with libhello.h as its header. File demo_use.c is a trivial caller of the library. This is followed by commented scripts (script_static and script_dynamic) showing how to use the library as a static and shared library. This is followed by demo_dynamic.c and script_dynamic, which show how to use the shared library as a dynamically loaded library.

File libhello.c

/* libhello.c - demonstrate library use. */

#include <stdio.h>

void hello(void) {
printf("Hello, library world.\n");
}
//------------------------------------------------------------------

File libhello.h

/* libhello.h - demonstrate library use. */

void hello(void);
//------------------------------------------------------------------

File demo_use.c

/* demo_use.c -- demonstrate direct use of the "hello" routine */

#include <libhello.h>

int main(void) {
hello();
return 0;
}
//------------------------------------------------------------------

File script_static

#!/bin/sh
# Static library demo

# Create static library's object file, libhello-static.o.
# I'm using the name libhello-static to clearly
# differentiate the static library from the
# dynamic library examples, but you don't need to use
# "-static" in the names of your
# object files or static libraries.

gcc -Wall -g -c -o libhello-static.o libhello.c
//------------------------------------------------------------------

# Create static library.
ar rcs libhello-static.a libhello-static.o
//------------------------------------------------------------------

# At this point we could just copy libhello-static.a
# somewhere else to use it.
# For demo purposes, we'll just keep the library
# in the current directory.

# Compile demo_use program file.

gcc -Wall -g -c demo_use.c -o demo_use.o
//------------------------------------------------------------------

# Create demo_use program; -L. causes "." to be searched during
# creation of the program. Note that this command causes
# the relevant object file in libhello-static.a to be
# incorporated into file demo_use_static.

gcc -g -o demo_use_static demo_use.o -L. -lhello-static
//------------------------------------------------------------------

# Execute the program.

./demo_use_static
//------------------------------------------------------------------
//------------------------------------------------------------------

File script_shared

#!/bin/sh
# Shared library demo

# Create shared library's object file, libhello.o.

gcc -fPIC -Wall -g -c libhello.c
//------------------------------------------------------------------

# Create shared library.
# Use -lc to link it against C library, since libhello
# depends on the C library.

gcc -g -shared -Wl,-soname,libhello.so.0 \
-o libhello.so.0.0 libhello.o -lc
//------------------------------------------------------------------

# At this point we could just copy libhello.so.0.0 into
# some directory, say /usr/local/lib.

# Now we need to call ldconfig to fix up the symbolic links.

# Set up the soname. We could just execute:
# ln -sf libhello.so.0.0 libhello.so.0
# but let's let ldconfig figure it out.

/sbin/ldconfig -n .
//------------------------------------------------------------------

# Set up the linker name.
# In a more sophisticated setting, we'd need to make
# sure that if there was an existing linker name,
# and if so, check if it should stay or not.

ln -sf libhello.so.0 libhello.so
//------------------------------------------------------------------

# Compile demo_use program file.

gcc -Wall -g -c demo_use.c -o demo_use.o
//------------------------------------------------------------------

# Create program demo_use.
# The -L. causes "." to be searched during creation
# of the program; note that this does NOT mean that "."
# will be searched when the program is executed.

gcc -g -o demo_use demo_use.o -L. -lhello
//------------------------------------------------------------------

# Execute the program. Note that we need to tell the program
# where the shared library is, using LD_LIBRARY_PATH.

LD_LIBRARY_PATH="." ./demo_use
//------------------------------------------------------------------
//------------------------------------------------------------------

File demo_dynamic.c

/* demo_dynamic.c -- demonstrate dynamic loading and
use of the "hello" routine */

/* Need dlfcn.h for the routines to
dynamically load libraries */

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

/* Note that we don't have to include "libhello.h".
However, we do need to specify something related;
we need to specify a type that will hold the value
we're going to get from dlsym(). */

/* The type "simple_demo_function" describes a function that
takes no arguments, and returns no value: */

typedef void (*simple_demo_function)(void);


int main(void) {
const char *error;
void *module;
simple_demo_function demo_function;

/* Load dynamically loaded library */
module = dlopen("libhello.so", RTLD_LAZY);
if (!module) {
fprintf(stderr, "Couldn't open libhello.so: %s\n",
dlerror());
exit(1);
}

/* Get symbol */
dlerror();
demo_function = dlsym(module, "hello");
if ((error = dlerror())) {
fprintf(stderr, "Couldn't find hello: %s\n", error);
exit(1);
}

/* Now call the function in the DL library */
(*demo_function)();

/* All done, close things cleanly */
dlclose(module);
return 0;
}
//------------------------------------------------------------------

File script_dynamic

#!/bin/sh
# Dynamically loaded library demo

# Presume that libhello.so and friends have
# been created (see dynamic example).

# Compile demo_dynamic program file into an object file.

gcc -Wall -g -c demo_dynamic.c
//------------------------------------------------------------------

# Create program demo_use.
# Note that we don't have to tell it where to search for DL libraries,
# since the only special library this program uses won't be
# loaded until after the program starts up.
# However, we DO need the option -ldl to include the library
# that loads the DL libraries.

gcc -g -o demo_dynamic demo_dynamic.o -ldl
//------------------------------------------------------------------

# Execute the program. Note that we need to tell the
# program where get the dynamically loaded library,
# using LD_LIBRARY_PATH.

LD_LIBRARY_PATH="." ./demo_dynamic
//------------------------------------------------------------------

Monday, December 21, 2009

Boost Vector Example

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Boost Vector Example
// Boost Vector operations Resize, Insert, Remove, Erase
// Date : 19 - Jun -2008
// Author: Prakhar Dubey (prakharprakhar@gmail.com)
// Compile: g++ vector.cpp -o vector -I path_to_boost -lboost_system-gcc43-mt-1_39
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/io.hpp>

int main () {

using namespace boost::numeric::ublas;
vector<double> v (10);

for (unsigned i = 0; i < v.size (); ++ i)
v (i) = i;

std::cout << v << std::endl;

//Using functions of vector
v.resize(15,1);
std::cout << "nsize increased to 15 "<< v << std::endl;

v.resize(10,1);
std::cout << v << std::endl;

v.insert_element(0,10);
std::cout << "nInserted 10 " << v << std::endl;

v.erase_element(0);
std::cout << "nRemoving " << v << std::endl;

v.clear();
std::cout << "nClearing " << v << std::endl;

}

OUTPUT:
[10](0,1,2,3,4,5,6,7,8,9)

size increased to 15
[15](0,1,2,3,4,5,6,7,8,9,0,0,0,0,0)

[10](0,1,2,3,4,5,6,7,8,9)

Inserted 10
[10](10,1,2,3,4,5,6,7,8,9)

Removing
[10](0,1,2,3,4,5,6,7,8,9)

Clearing
[10](0,0,0,0,0,0,0,0,0,0)

Boost Thread Example

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Boost Simple Thread Example
// Date : 19 - Jun -2008
// Author: Prakhar Dubey (prakharprakhar@gmail.com)
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

#include <boost/thread/thread.hpp>
#include <iostream>

void hello()
{
std::cout << "Hello world, I'm a thread!" << std::endl;
}

int main(int argc, char* argv[])
{
boost::thread thrd(&hello);
thrd.join();
return 0;
}

STL Map Example

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// STL Map Example
// Map operations Insert, Find, Iterate
// Date : 19 - Jun -2008
// Author: Prakhar Dubey (prakharprakhar@gmail.com)
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

#include <iostream>
#include <stdlib.h>
#include <map>
#include <string.h>
using namespace std;


typedef struct NODE{
int x;
char domain[64];
char *xdomain;
}NODE;

map<char *,NODE> mymap;
map<char *,NODE>::iterator it;
int main ()
{
NODE n1,n2,n3,n4;
n1.x= 1;
n2.x= 2;
n3.x= 3;
strcpy(n1.domain,"hello1");
strcpy(n2.domain,"hello2");
strcpy(n3.domain,"hello3");

char *str = "abcd";

mymap["abc"]=n1;
mymap["ab"] =n2;
mymap["abcd"] =n3;

it = mymap.find(str);
cout << "it = " << it->second.domain << endl;;

//print content:
cout << "elements in mymap:" << endl;
for ( it = mymap.begin(); it != mymap.end(); it++)
{
cout << "elements in mymapi is : "<< it->second.domain << " " <<it->first << endl;
}
return 0;
}

Boost Shared Memory Vector Reader

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Boost Shared Memory Reader
// This vector is read from a shared memory
// Date : 26 - July -2009
// Author: Prakhar Dubey (prakharprakhar@gmail.com)
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/allocators/allocator.hpp>

#include <iterator>
#include <functional>
#include <utility>
#include <sys/time.h>
#include <time.h>
#include <iostream>

#define NUM_ENTRIES 10

int main ()
{
using namespace boost::interprocess;

typedef allocator<int, managed_shared_memory::segment_manager> ShmemAllocator;
typedef vector<int, ShmemAllocator> MyVector;

try{
//Open the managed segment
managed_shared_memory segment(open_only, "MySharedMemory");
//Find the vector using the c-string name
MyVector *myvector = segment.find<MyVector>("MyVector").first;

//size of vector
std::cout << "size = " << myvector->size() << std::endl;


MyVector::iterator iter = myvector->begin();
while(iter++ != myvector->end())
std::cout << "nvalue = " << *iter ;


//When done, destroy the vector from the segment
//segment.destroy<MyVector>("MyVector");
}
catch(...){
std::cout<<"n Exception caught";
throw;
}
return 0;
}

Boost Shared Memory Vector

/^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Boost Shared Memory
// This vector is stored in a shared memory
// Date : 26 - July -2009
// Author: Prakhar Dubey (prakharprakhar@gmail.com)
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <string>
#include <cstdlib> //std::system

using namespace boost::interprocess;

/* Define an STL compatible allocator of ints that allocates from the managed_shared_memory.
This allocator will allow placing containers in the segment */

typedef allocator<int, managed_shared_memory::segment_manager> ShmemAllocator;

/* Alias a vector that uses the previous STL-like allocator so that allocates
its values from the segment */

typedef vector<int, ShmemAllocator> MyVector;

/* Main function. For parent process argc == 1, for child process argc == 2 */

int main(int argc, char *argv[])
{
shared_memory_object::remove("MySharedMemory");

//Create a new segment with given name and size
managed_shared_memory segment(create_only, "MySharedMemory", 65536);

//Initialize shared memory STL-compatible allocator
const ShmemAllocator alloc_inst (segment.get_segment_manager());

//Construct a vector named "MyVector" in shared memory with argument alloc_inst
MyVector *myvector = segment.construct<MyVector>("MyVector")(alloc_inst);

for(int i = 0; i < 100; ++i) //Insert data in the vector
myvector->push_back(i);

return 0;
}

Producer Consumer Problem

/^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// A Producer Consumer Problem
// Message Queue with single producer and single consumer
// Try the same program without using locks
// Date : 26 - July -2009
// Author: Prakhar Dubey (prakharprakhar@gmail.com)
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

#include <pthread.h>
#include <queue>
#include <stdio.h>
#include <unistd.h>
#define MAX_SIZE 100000

using namespace std;
pthread_cond_t condition;
pthread_mutex_t my_mutex;

queue <int> cb;

void *ProducerFunc(void *x)
{
// Insert some elements into the buffer.
printf("Producer Threadn");

int i;
for (i=0;i<MAX_SIZE;i++)
{
//printf("inside for loop Producer Threadn");
pthread_mutex_lock(&my_mutex);
cb.push(i);

pthread_cond_signal(&condition);
pthread_mutex_unlock(&my_mutex);
}
pthread_exit(NULL);

}

void *ConsumerFunc(void *x)
{
printf("Consumer Threadn");
int i;
while(1)
{
pthread_mutex_lock(&my_mutex);
pthread_cond_wait(&condition, &my_mutex);

while(!cb.empty())
{
printf("Deleted value is = %dn",cb.front());
cb.pop();
}
pthread_mutex_unlock(&my_mutex);
}

pthread_exit(NULL);
}


int main()
{
pthread_t producer, consumer;
pthread_cond_init(&condition, NULL);
pthread_mutex_init(&my_mutex, NULL);

int rc1 = pthread_create(&producer, NULL, ProducerFunc, NULL);
int rc2 = pthread_create(&consumer, NULL, ConsumerFunc, NULL);
if (rc1 || rc2)
{
printf("ERROR; return code from pthread_create() is %dn", rc1);
return 0;
}
pthread_join(producer, NULL);
pthread_join(consumer, NULL);


pthread_mutex_destroy(&my_mutex);
pthread_cond_destroy(&condition);
pthread_exit(NULL);

return 0;
}

Boost Message Queue (Interprocess) Receiver

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// InterProcess Message Queue with Boost::interprocess
// Message Queue Receiver
// Date : 26 - Nov -2009
// Author: Prakhar Dubey (prakharprakhar@gmail.com)
// Compile: g++ mq_receiver.cpp -o mq_receiver -I path_to_boost -lboost_system-gcc43-mt-1_39
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


#include <boost/interprocess/ipc/message_queue.hpp>
#include <iostream>
#include <vector>
#include <boost/asio.hpp>

using namespace boost::interprocess;

// Structure to be read
typedef struct s_Request{
int src_ip,des_ip;
boost::asio::ip::address objRequest;
char name[50];
}st_Request;

int main ()
{
try{
//Open a message queue.
message_queue mq
(open_only //only create
,"message_queue" //name
);

unsigned int priority;
std::size_t recvd_size;

//Receive 100 numbers
/*for(int i = 0; i < 100; ++i){
int number;
mq.receive(&number, sizeof(number), recvd_size, priority);
if(number != i || recvd_size != sizeof(number))
return 1;
else
std::cout << "nnumber = " << number;
}*/
//Receive Structure
st_Request dataone, datatwo;
mq.receive(&dataone, sizeof(st_Request), recvd_size, priority);
if(recvd_size != sizeof(st_Request))
return 1;
else{
std::cout << "nsrcip = " << dataone.src_ip;
std::cout << "ndesip = " << dataone.des_ip;
std::cout << "nRequest = " << dataone.objRequest.to_string();
std::cout << "nname = " << dataone.name;
}
}
catch(interprocess_exception &ex){
message_queue::remove("message_queue");
std::cout << ex.what() << std::endl;
return 1;
}
message_queue::remove("message_queue");
return 0;
}

Boost Message Queue (Interprocess) Sender

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// InterProcess Message Queue with Boost::interprocess
// Message Queue Sender
// Date : 26 - Nov -2009
// Author: Prakhar Dubey (prakharprakhar@gmail.com)
// Compile: g++ mq_sender.cpp -o mq_sender -I path_to_boost -lboost_system-gcc43-mt-1_39
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


#include <boost/interprocess/ipc/message_queue.hpp>
#include <iostream>
#include <vector>
#include <boost/asio.hpp>

using namespace boost::interprocess;

// Any structure to be send to message queue
typedef struct s_Request{
int src_ip,des_ip;
boost::asio::ip::address clientAddress;
char name[50];
}st_Request;

int main ()
{
try{
//Create data to be entered
st_Request data1 = {10,20,boost::asio::ip::address::from_string("10.31.141.45"),"www.google.com"};

st_Request data2 = {40,50,boost::asio::ip::address::from_string("192.168.64.152") ,"www.rediff.com"};



//Erase previous message queue
message_queue::remove("message_queue");
//Create a message_queue.
message_queue mq
(create_only //only create
,"message_queue" //name
,100 //max message number
,sizeof(st_Request) //max message size
);

//Send 100 numbers
//for(int i = 0; i < 100; ++i){
// mq.send(&i, sizeof(i), 0);
//}

//Send 2 structures
mq.send(&data1, sizeof(st_Request), 0);
mq.send(&data2, sizeof(st_Request), 0);
}
catch(interprocess_exception &ex){
std::cout << ex.what() << std::endl;
return 1;
}
return 0;
}

Boost timer

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Boost asynchronous timer.
// Date : 26 - Nov -2009
// Author: Prakhar Dubey (prakharprakhar@gmail.com)
// Compile: g++ timer.cpp -o timer -I path_to_boost -lboost_system-gcc43-mt-1_39
// Execute: ./timer
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

void print(const boost::system::error_code& /*e*/)
{
std::cout << "Hello, world!n";
}

int main()
{
boost::asio::io_service io;

boost::asio::deadline_timer t(io,boost::posix_time::seconds(3));
t.async_wait(print);
io.run();

return 0;
}

UDP Listener/Receiver with libevent

UDP Listener/Receiver with libevent
Timer with lib event


//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// The program listens on multiple udp sockets simultaneously
// and calling the event on them.
// Date : 26 - Nov -2009
// Author: Prakhar Dubey (prakharprakhar@gmail.com)
// Compile: g++ event_test.c -o event_test -levent
// Execture: ./event_test 0 10
// Listen on 10 udp ports starting from 6000 to 6009.
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

#define UDP_PORT 6000
#include <iostream>
#include <event.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

using namespace std;

int g_count = 0;
struct timeval stTv;

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// TIMER FUNCTION
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
void timer_function(int x, short int y, void *pargs)
{
printf("nn**********Count is %dnn",g_count);
g_count = 0 ;
event_add((struct event*)pargs,&stTv);
}



//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Event Function
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
void func_for_eve1(int x, short int y, void *pargs)
{
unsigned int unFromAddrLen;
int nByte = 0;
char aReqBuffer[512];
struct sockaddr_in stFromAddr;

unFromAddrLen = sizeof(stFromAddr);

if ((nByte = recvfrom(x, aReqBuffer, sizeof(aReqBuffer), 0,
(struct sockaddr *)&stFromAddr, &unFromAddrLen)) == -1)
{
printf("error occured while receivingn");
}

//printf("Function called buffer is %sn",aReqBuffer);
g_count++;

}

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// MAIN
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
int main(int argc, char **argv)
{
struct event_base *base ;
struct event g_Timer;
int val1,val2;
if(argc == 3)
{
val1 = atoi(argv[1]);
val2 = atoi(argv[2]);
printf("Value is %d %dn",val1,val2);
}
else return 0;

struct event g_eve[val2-val1];
int udpsock_fd[val2-val1];
struct sockaddr_in stAddr[val2-val1];

base = event_init();

for(int i=0; i< val2-val1 ; i++)
{
if ((udpsock_fd[i] = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
printf("ERROR - unable to create socket:n");
exit(-1);
}

//Start : Set flags in non-blocking mode
int nReqFlags = fcntl(udpsock_fd[i], F_GETFL, 0);
if (nReqFlags< 0)
{
printf("ERROR - cannot set socket options");
}

if (fcntl(udpsock_fd[i], F_SETFL, nReqFlags | O_NONBLOCK) < 0)
{
printf("ERROR - cannot set socket options");
}
// End: Set flags in non-blocking mode
memset(&stAddr[i], 0, sizeof(struct sockaddr_in));
//stAddr.sin_addr.s_addr = inet_addr("192.168.64.1555552");
stAddr[i].sin_addr.s_addr = INADDR_ANY; //listening on local ip
stAddr[i].sin_port = htons(UDP_PORT+i+val1);
stAddr[i].sin_family = AF_INET;


int nOptVal = 1;
if (setsockopt(udpsock_fd[i], SOL_SOCKET, SO_REUSEADDR,
(const void *)&nOptVal, sizeof(nOptVal)))
{
printf("ERROR - socketOptions: Error at Setsockopt");

}

if (bind(udpsock_fd[i], (struct sockaddr *)&stAddr[i], sizeof(stAddr[i])) != 0)
{
printf("Error: Unable to bind the default IP n");
exit(-1);
}

event_set(&g_eve[i], udpsock_fd[i], EV_READ | EV_PERSIST, func_for_eve1, &g_eve[i]);
event_add(&g_eve[i], NULL);
}

/////////////TIMER START///////////////////////////////////
stTv.tv_sec = 3;
stTv.tv_usec = 0;
event_set(&g_Timer, -1, EV_TIMEOUT , timer_function, &g_Timer);
event_add(&g_Timer, &stTv);
////////////TIMER END/////////////////////////////////////

event_base_dispatch(base);
return 0;
}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

UDP Sender C Program

A Program which sends udp packet to a defined port PORT.
Set SRV_IP of the receiving server,
Number of Packets = NPACK * 1000 * 1000

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

#define BUFLEN 512
#define NPACK 10
#define PORT 6000

void diep(char *s)
{
perror(s);
exit(1);
}

int main(void)
{
struct sockaddr_in si_other;
long int j;
int fd, slen=sizeof(si_other);
char buf[BUFLEN];

int i;
{
if ((fd=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
diep("socket");

memset((char *) &si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);

if (inet_aton(SRV_IP, &si_other.sin_addr)==0)
{
fprintf(stderr, "inet_aton() failedn");
exit(1);
}
}

for (j=0; j<NPACK * 1000 * 1000; j++)
{
sprintf(buf, "512 length string you can type here anything this is so and so packetn");
if (sendto(fd, buf, BUFLEN, 0, &si_other, slen)==-1)
diep("sendto()");
}
close(fd);
return 0;
}

strtok Example

Tokenizing at '*' and '/'

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


int
main() {
char *token;
char *lasts;
char buf[50] ;

strcpy(buf,"3/4/5/**6*7");
printf("ntokenizing %s with strtok_r():n", buf);

if ((token = strtok_r(buf, "*/", &lasts)) != NULL) {
printf("token = %sn", token);
while ((token = strtok_r(NULL, "*/", &lasts)) != NULL) {
printf("token = %sn", token);
}
}
}


OUTPUT:
tokenizing 3/4/5/**6*7 with strtok_r():
token = 3
token = 4
token = 5
token = 6
token = 7

sscanf with expression

Using expression with sscanf

int main()
{
char rangestr = "10.32.125.224 - 220.12.32.52";
char ip1[16], ip2[16];
retval = sscanf(rangestr, "%[^'-'] - %s", ip1,ip2);
printf ("return calue = %d ip1 = %s, ip2 = %s",retval,ip1,ip2);

return 0;
}

%[^'-'] = From '^' start read till '-' character

System V Message queue

System V Message Queue

Message Queue Sender Program
//-----------------------------------------------------------------//
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>

struct my_msgbuf {
long mtype;
char mtext[1000];
//char mtext;
};

int main(void)
{
struct my_msgbuf buf;
int msqid;
key_t key = 2221;

if ((msqid = msgget(key, 0666 | IPC_CREAT)) < 0) {
perror("msgget");
exit(1);
}
printf("nmsgqid %dn", msqid);

buf.mtype = 1;
strcpy(buf.mtext,"hello world ");
size_t len = sizeof(struct my_msgbuf) - sizeof(long);
printf("len %dn", len);

struct msqid_ds buf_ds;
while(1)
{
sleep(2);
if (msgsnd(msqid, &buf, len, IPC_NOWAIT) < 0)
{
// if message queue is full increase the message queue size
if(msgctl(msqid, IPC_STAT, &buf_ds) < 0)
{
perror("msgctl:get");
exit(1);
}

buf_ds.msg_qbytes += 16*1024;
if(msgctl(msqid, IPC_SET, &buf_ds) < 0)
{
perror("msgctl:set");
exit(1);
}

if (msgsnd(msqid, &buf, len, IPC_NOWAIT) < 0)
{
perror("msgsnd");
exit(1);
}
}
}
return 0;
}
//-----------------------------------------------------------------//


Message Queue Receiver Program
//-----------------------------------------------------------------//
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>

#define MSGSZ 1000

/*Declare the message structure*/

typedef struct my_msgbuf {
long mtype;
char mtext[1000];
//char mtext;
} message_buf;

main()
{
int msqid;
key_t key;
message_buf rbuf;

/*
*Get the message queue id for the
* "name" 2221, which was created by
* the server.
*/
key = 2221;

if ((msqid = msgget(key, 0666)) < 0) {
perror("msgget");
return (0);
}

while(1)
{
if (msgrcv(msqid, &rbuf, MSGSZ, 1, 0) < 0) {
perror("msgrcv");
return(0);
}

/*Print the answer*/

printf("%sn", rbuf.mtext);
}
return (0);
}
//-----------------------------------------------------------------//

Syslog Example

Start logging with syslog, system logging utility.

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

int main(void) {
int i;
setlogmask (LOG_UPTO (LOG_NOTICE));
openlog ("exampleprog", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_USER);

for (i = 0;i<20000;i++)
{
syslog (LOG_NOTICE, "Program started by User %d", getuid ());
syslog (LOG_INFO, "A tree falls in a forest");

}
setlogmask (LOG_UPTO (LOG_INFO));
for (i = 0;i<20000;i++)
{
syslog (LOG_NOTICE, "Program started by User %d", getuid ());
syslog (LOG_INFO, "A tree falls in a forest");

}
closelog ();


return 0;
}

Signal Handling

An example of signal handling in C.


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

void
termination_handler (int signum)
{
printf("signal called number %dn", signum);
if(signum == SIGUSR1)
signal (SIGUSR1, termination_handler);
//if(signum == SIGINT)
//signal (SIGINT, termination_handler);
if(signum == SIGUSR2)
signal (SIGUSR2, termination_handler);
}

int main (void)
{
{
signal (SIGUSR1, termination_handler);
perror("??");
signal (SIGUSR2, termination_handler);
perror("??");
//signal (SIGINT, termination_handler);
//perror("??");
}

while(1)
{
sleep(100);
printf("");
}

}

STD Merge

A very simple example using merge algorithm. Two arrays merged into a vector.
Merge algorithm requires arrays to be sorted first.


#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main () {
int first[] = {5,10,15,20,25};
int second[] = {50,40,30,20,10};
vector<int> v(10);
vector<int>::iterator it;

sort (first,first+5);
sort (second,second+5);
merge (first,first+5,second,second+5,v.begin());

cout << "The resulting vector contains:";
for (it=v.begin(); it!=v.end(); ++it)
cout << " " << *it;

cout << endl;

return 0;
}