Showing posts with label Ubuntu. Show all posts
Showing posts with label Ubuntu. Show all posts

Tuesday, August 12, 2014

boost::array of Integers in Qt Creator

boost::array provides C-style array declaration and usage with constant number of items inside it. When only static-constant sized arrays are required, then boost::array comes with a better memory management solution than std::vector.

After including boost libraries into a Qt Creator C++ project, it becomes easy to use boost::array type of members in your programs.

boost/array.hpp file contains boost::array type.

As the boost::array documentation indicates boost::array is the STL compliant container wrapper for arrays of constant size.



Following sample project created by qt creator and contains following files:

1- BoostArrayOfIntegers.pro
2- main.cpp


BoostArrayOfIntegers.pro file contains project configuration.
TEMPLATE = app
CONFIG += console

SOURCES += main.cpp

INCLUDEPATH += /home/tufan/boost_1_55_0

I have installed the boost library to the directory         :  /home/tufan/boost_1_55_0
and boost/array.hpp file is located at                           :  /home/tufan/boost_1_55_0/boost/array.hpp

so qt creator does not complain about path related errors.


There is also another installed boost library which contains an older version of boost libraries  at directory : /usr/include/boost


In BoostArrayOfIntegers.pro file I have stated that I will use the boost library from specific location and qt creator selected the library from : /home/tufan/boost_1_55_0


main.cpp file contains main method.

#include <boost/array.hpp>

using namespace std;

int main()
{
    typedef boost::array<int, 4> intArrayType;
    intArrayType myArray = {{1,2,3,4}};
    std::cout << "boost intArray content :" << "\n";
    for( intArrayType::const_iterator iterator = myArray.begin(),
         iteratorEnd = myArray.end();
         iterator != iteratorEnd; ++iterator )
    {
        cout << *iterator << endl;
    }

    return 0;
}
boost::array is initialized with 4 integer members in curly braces. I used an iterator to traverse the integer members of the boost::array.

When the project is executed the following terminal output is generated :

boost intArray content :
1
2
3
4

Saturday, April 17, 2010

Installing Fast Debugger for NetBeans 6.8 on Ubuntu 9.10

NetBeans IDE enables RoR developers to set break points in specific parts of source files. It is time consuming to use print statements to trace application development process. Because Fast Debugger uses native C extensions, gcc and some other extra packages need to be installed on your Ubuntu 9.10:

$ sudo apt-get install build-essential autoconf

Above command installed the following extra packages :
automake autotools-dev dpkg-dev fakeroot g++ g++-4.4 libstdc++6-4.4-dev m4
patch

Now you need to install ruby1.8-dev package to compile any native extensions.

$ sudo apt-get install ruby1.8-dev

Above command installed ruby1.8-dev package.
Now the ruby-debug-ide gem should build successfully.

$ gem install ruby-debug-ide
Building native extensions. This could take a while...
Successfully installed ruby-debug-ide-0.4.9
1 gem installed
Installing ri documentation for ruby-debug-ide-0.4.9...
Installing RDoc documentation for ruby-debug-ide-0.4.9...

NetBeans automatically detected Fast Debugger.$ gem list

*** LOCAL GEMS ***

actionmailer (2.3.4, 2.3.2)
actionpack (2.3.4, 2.3.2)
activerecord (2.3.4, 2.3.2)
activeresource (2.3.4, 2.3.2)
activesupport (2.3.4, 2.3.2)
linecache (0.43)
rack (1.0.1)
rails (2.3.4, 2.3.2)
rake (0.8.7)
ruby-debug-base (0.10.3)
ruby-debug-ide (0.4.9)

Monday, November 23, 2009

Set JAVA_HOME and PATH on ubuntu 9.10

Instead of installing JDK from synaptic package manager, you can manually download JDK 6 Update 17 from http://java.sun.com/javase/downloads/index.jsp. After downloading "jdk-6u17-linux-i586.bin", make it executable by changing its mode and run to install by issuing following commands.

$ chmod 777 jdk-6u17-linux-i586.bin
$ ./java_ee_sdk-5_08-jdk-6u17-linux.bin

After that point edit your /etc/profile file to add lines below:
$ sudo gedit /etc/profile

PATH=(yourJDKInstallationFolder)/bin:${PATH}
export PATH
JAVA_HOME=(yourJDKInstallationFolder)
export JAVA_HOME

Save /etc/profile and logout. To test your JAVA_HOME location and installed java version type from the console:
$ java -version

$ echo $JAVA_HOME

Friday, October 9, 2009

Shutdown Remote Ubuntu Machine

SSH protocol is used to exchange data between two networked devices using a secure channel. Ubuntu server machines with ssh installed on them can be reached from other computers on the network. Ubuntu's synaptic package manager easily installs ssh for your server machine. In order to reach remote ubuntu server machines with ssh installed on them, type the following command from command line of the client machine:
$ ssh remoteUserName@remoteMachineIPAddress
replace remoteUserName and remoteMachineIPAddress with appropriate values. Then you will see that it is asking for adding to the list of known hosts. write 'yes' for confirmation. Then type following from the console window and press enter, the remote machine will shutdown.
$ sudo shutdown -h now

Friday, May 22, 2009

TCP Echo Client Server

When writing a TCP client server program in unix environment, elementary socket functions are used.As described at Stevens book these elementary functions are listed as:

-socket : To perform network I/O, the first thing a process must do is call the socket function.
-connect : used by a TCP client to establish a connection with a TCP server.
-bind : assigns a local protocol address to a socket.
-listen : called by only a TCP server and it converts an unconnected socket into a passive socket.
-accept :called by a TCP server to return the next completed connection from the front of the completed connection queue.
-fork :In Unix environment it is used to create a new process. By using fork() a process makes a copy of itself so that one copy can handle one operation while the other does another task.
-close : close a socket and terminate a TCP connection.

By using above elementary functions we can build our simple echo client and server programs. In this program, when a client connects to the server, the server will use fork() to create a new child process.

Newly created child process will serve the client. The child process terminates after the client sends its message and breaks the connection. The algorithm is as follows:

If this is the child process:
- Close listenfd since it is the responsibility of the parent to handle incoming connections.
- Display the message "Child process serving the client."
- Read the message from the client and display it.
- Close connectfd.
- Exit. The child process was created only to serve the client.

Since the client has transmitted its message and the connection is terminated, the child must terminate.

If this is the parent process:
- Close connectfd since it is the responsibility of the child process to serve the client.
- Go back to accept. Note that the server (parent) runs indefinitely.

client-source.c file is as follows:

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/in.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main(int argc,char **argv)
{
    int clientfd;
    short int port_no;
    char msg[1000];
    struct sockaddr_in servaddr;
    char *server_ip_address;
    if(argc!=5){
       printf("Usage Format: ./client -a <IPAddress> -p <PortNumber>\n");
       printf("Sample Run: ./client -a 127.0.0.1 -p 2000\n");
       exit(1);
    }
    server_ip_address=(char *)argv[2];
    port_no = atoi(argv[4]);
    printf("Client will connect to the server at IP %s, port #%d\n", server_ip_address, port_no);
   
    // Create client socket.
    if((clientfd = socket(AF_INET, SOCK_STREAM, 0))<0 br="">       printf("Socket could not be created\n");
       printf("errno %i: %s\n",errno,strerror(errno));
       exit(1);
    }
    printf("Client socket created\n");
    errno=0;
    // Connect to the server client
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(port_no);
    if((inet_pton(AF_INET, server_ip_address, &servaddr.sin_addr))<=0){
      printf("inet_pton error for %s\n",server_ip_address);
      printf("errno %d: %s\n",errno,strerror(errno));
      exit(1);
    }
    errno=0;
    if((connect(clientfd, (struct sockaddr *) &servaddr, sizeof(servaddr)))<0 br="">      printf("Connect error\n");
      printf("errno %d: %s\n",errno,strerror(errno));
      exit(1);
    }
    printf("Client socket connected\n");
    // Read one line of message from the input and send it to the server.
    printf("Enter the message to be sent to the server: ");
    scanf("%s", msg);
    send(clientfd, msg, strlen(msg)+1, 0);
    close(clientfd);
    printf("Client sent the message and disconnected. \n");
    return 0;
}


server-source.c file is as follows:

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/in.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
extern int errno;
int main(int argc,char **argv)
{
    int clientaddrlen, listenfd, connectfd, bytes_rcvd, listen_queue_size=1;
    short int port_no;
    char buffer[1000];
    struct sockaddr_in servaddr, clientaddr;
    pid_t  childpid;
    int status;
    if(argc!=3){
       printf("Usage Format: ./server -p <PortNumber>\n");
       printf("Sample Run: ./server -p 2000\n");
       exit(1);
    }
    port_no = atoi(argv[argc-1]);
    printf("Server running at port #%d\n", port_no);

    // Create server socket.
    if ( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
        fprintf(stderr, "Cannot create server socket! errno %i: %s\n",errno,strerror(errno));
        exit(1);
    }
    printf("Server socket created\n");
    // Bind (attach) this process to the server socket.
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(port_no);
    errno = bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
    if(errno < 0){
        printf("Server bind failure errno %i: %s\n",errno,strerror(errno));
        exit(1);
    }
    printf("Server socket is bound to port #%d\n", port_no);
    // Turn 'listenfd' to a listening socket. Listen queue size is 1.
    errno=listen(listenfd,listen_queue_size);
    if(errno < 0){
        printf("Server listen failure errno %i: %s\n",errno,strerror(errno));
        exit(1);
    }
    printf("Server listening with a queue of size %d. \n", listen_queue_size);
    // Wait for connection(s) from client(s).
    while (1){
        clientaddrlen = sizeof(clientaddr);
        connectfd = accept(listenfd, (struct sockaddr *) &clientaddr, &clientaddrlen);
        if(connectfd<0 br="">            printf("Server accept failure errno %d: %s\n",errno,strerror(errno));
            exit(1);
        }
        printf("A connection received from a client. Creating a child to serve the client.\n");
        if((childpid = fork()) == 0) { /* child process */
           close(listenfd); /* close listening socket */
           printf("Child process serving the client.\n");
           if (recv(connectfd, buffer, sizeof(buffer), 0 ) > 0){
               printf("Received message: %s\n", buffer);
           }
        close(connectfd);   /* parent closes connected socket */
        exit(1);
        }
        else if (childpid <0 br="" failed="" fork="" to="">             printf("Failed to fork\n");    
             printf("Fork error errno %d: %s\n",errno,strerror(errno));
        }
        else if(childpid != 0){  /* parent process */
             close(connectfd);   /* parent closes connected socket */  
             childpid = wait(&status);  
        }
    }
    return 0;
}

In order to avoid zombie processes created in the system, wait() function is used in the server main function.

Sample run can be created as follows:

1-)Create server and client executables :

$ cc -o server server_source.c
$ cc -o client client_source.c

2-)Run server at the same tab

$ ./server -p 2000

3-)Open a new tab, run client

$ ./client -a 127.0.0.1 -p 2000

You can get client_source.c and server_source.c files from the links.Application tested on ubuntu9.04.

Friday, April 24, 2009

Distributed Systems Programming with rpcgen

rpcgen utility enables developers to write distributed applications.

It generates stubs for client and server side automatically. Programmer is required to write 3 additional programs to use rpcgen tool.

You need to have rpcgen utility installed on your machine to run the example. Ubuntu synaptic easily installs it for you.

1-) Write the prog.x file which contains definition for required routines. You can give any name for this *.x file ending with .x extension.You need to declare remote procedures in a remote program.

/*  prog.x
                                                                
 * Define your procedure here
 
 * function_1 dir_list_1(string) returns the output to the client 
 * (takes one string argument)

 * function_2 execute_uptime_1() returns the output to the client 
 * (no argument)
*/    
program RPC_PROG {                                               
    version RPC_VERS {                                         
    string DIR_LIST(string) = 1; /* procedure number = 1 */
    string EXECUTE_UPTIME(void) = 2; /* procedure number = 2 */
    } = 1; /* version number = 1 */
} = 0x12345678; /* program number = 0x12345678 */


2-) Write remote procedure implementation in a *.c file.

This file contains implementation of procedures declared in prog.x file.

/*  server_source.c   */  
#include <time.h>
#include <rpc/rpc.h> /* standard RPC include file */
#include "prog.h" /* this file is generated by rpcgen */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define READ_MAX_SIZE 512

/*Return the listing of all files in a directory function1*/
char** dir_list_1_svc(char** location, struct svc_req* arg2)
{
 FILE* fpipe;
 char* command="ls -l ";
 char* commandAndDirName;
 static char* readPipeInto;
 readPipeInto = (char*)malloc((READ_MAX_SIZE + 1)*sizeof(char));
 memset(readPipeInto, 0, READ_MAX_SIZE + 1);
 commandAndDirName=(char*)malloc((strlen(command)+strlen(*location)+1)*sizeof(char));
 strcpy(commandAndDirName, command);
 strcat(commandAndDirName, *location);
 //execute command ls -l
 if ( !(fpipe = (FILE*)popen(commandAndDirName,"r")) )
 {
    perror("Cant open pipe!");
    exit(1);
 }
 //store result in readPipeInto
 fread((char*)readPipeInto, READ_MAX_SIZE, 1, fpipe); 
 pclose(fpipe); 
 free(commandAndDirName);
 //return output to the client
   return (char**)&readPipeInto;
}
/* Return the result of command uptime function2*/
char** execute_uptime_1_svc(void* arg1,struct svc_req* arg2)
{
 FILE* fpipe;
 char* command="uptime";
 static char* readPipeInto;
 readPipeInto = (char*)malloc((READ_MAX_SIZE + 1)*sizeof(char));
 memset(readPipeInto, 0, READ_MAX_SIZE + 1);
 //execute command uptime
 if ( !(fpipe = (FILE*)popen(command,"r")) )
 { 
    perror("Cant open pipe!");
    exit(1);
 }
 //store result in readPipeInto
 fread((char*)readPipeInto, READ_MAX_SIZE, 1, fpipe); 
 pclose(fpipe);
 //return output to the client
 return (char**)&readPipeInto;
}

1st procedure at server program
" char** dir_list_1_svc(char** location, struct svc_req* arg2) " 


corresponds to " string DIR_LIST(string) " procedure declaration in prog.x file.

DIR_LIST procedure takes a string directory location such as "/home" from client program as an input parameter and appends this parameter to "ls -l" program at server procedure.


So, output of "ls -l /home" is returned back to the client from the server.

For return values of procedures, one more level of indirection is added to each procedure signature and parameters at server side.


For the 1st procedure at client program "string DIR_LIST(string) ", return value is changed from (char*) to (char**) .

2nd procedure at server program
" char** execute_uptime_1_svc(void* arg1,struct svc_req* arg2) "
corresponds to " string EXECUTE_UPTIME(void) " procedure declaration in prog.x file.

EXECUTE_UPTIME(void) procedure does not take any parameter from the client and executes the external program "uptime". 


Result of execution is sent back to the client.

At both of the above procedure implementations, it is common that programs (ls -l and uptime) are executed at server side and the result is written into a pipe. 


Then command output is read from that pipe and returned back to the client side.

3-) Write the main client program that calls the remote procedures from server.




/* client_source.c file */

#include <stdio.h>
#include <stdlib.h>                                       
#include <rpc/rpc.h> /* standard RPC include file */     
#include "prog.h" /* this file is generated by rpcgen */ 
                    
main(int argc, char *argv[])                               
{ 
   CLIENT *cl; /* RPC handle */

   char *server;
   /* return value from dir_list_1() function1*/
   char** resultStringFromServerDirList;
   /* return value from execute_uptime_1 function2*/ 
   char** resultStringFromServerUptime; 
   if (argc != 2) {
       fprintf(stderr, "usage: %s hostname\n", argv[0]);
       exit(1);
   }

   server = argv[1];
   /* Create client handle */
   if ((cl = clnt_create(server, RPC_PROG, RPC_VERS, "udp")) == NULL) {
       /* can't establish connection with server */
       clnt_pcreateerror(server);
       exit(2);
   }
   char* directory = "/home";

   /* call remote procedure dir_list */
   resultStringFromServerDirList = dir_list_1((char**)&directory, cl);
   if (resultStringFromServerDirList == NULL) {
      clnt_perror(cl, server);
      exit(3);
   }
   printf("\n\n");
   printf("Function1 Result of Directory Listing is: \n\n");
   printf("%s",*resultStringFromServerDirList);
   printf("\n\n");

   /* call remote procedure execute_uptime */
   resultStringFromServerUptime = execute_uptime_1(NULL, cl);
   if (resultStringFromServerUptime == NULL) {
      clnt_perror(cl, server);
      exit(4);
   }
   printf("Function2 Result of Command uptime is: \n\n");
   printf("%s",*resultStringFromServerUptime);
   printf("\n\n");
   
   clnt_destroy(cl); 
   exit(0);
}

After writing those 3 files, you can use rpcgen tool to generate related client and server programs.


Put "client_source.c" "prog.x" and "server_source.c" files into the same folder. 

Then by using cc -o from the command line create client and server executables separately.


Sample Run:
------------------------------------------------------------
Prepare server and run from the console: Open your console to run following commands.

user@machine:~/Desktop/user$ rpcgen prog.x
user@machine:~/Desktop/user$ cc -o client client_source.c prog_clnt.c 
user@machine:~/Desktop/user$ cc -o server server_source.c prog_svc.c 
user@machine:~/Desktop/user$ ./server 


"rpcgen prog.x" command creates prog_clnt.c(client stub) prog_svc.c(server stub) and prog.h header file. 


At the end of successful compilation client and server executables are located in the same directory. Then open a new terminal tab and Run client:

user@machine:~/Desktop/user$ ./client localhost


Server returns the output of executed programs to the client.

user@machine:~/Desktop/user$ ./client localhost


Function1 Result of Directory Listing is: 

total 4
drwxr-xr-x 52 user user 4096 2009-04-25 01:04 user


Function2 Result of Command uptime is: 

 01:05:49 up  4:08,  3 users,  load average: 0.17, 0.36, 0.25


user@machine:~/Desktop/user$