Network Programming in GNU/LINUX:Introduction on building a server application in GNU/LINUX using C socket API’s

/*This is an Introduction on building a server application in GNU/LINUX using C socket API’s*/
/*Run this program and issue “netstat -ant | grep 7004” in another terminal, you can see the server listening */

/*accept system call doesnot return till either it encounters an error or gets a connection from a client(such system calls are called as blocking system call */
#include<sys/socket.h>
#include<netinet/in.h>
int main()
{
    int sd,len;
    struct sockaddr_in servaddr,cliaddr;//socket structure
    sd=socket(AF_INET,SOCK_STREAM,0);/*elementary call in any client server application to create an socket*/

    bzero(&servaddr,sizeof(servaddr));//to initialize all elements of the structure to zero
    servaddr.sin_addr.s_addr=htonl(INADDR_ANY);//To assian a arbitrary IP to the server
    servaddr.sin_family=AF_INET;
    servaddr.sin_port=htons(7004);//port on which the server listens
    bind(sd,(struct sockaddr *)&servaddr,sizeof(servaddr));/*assign the IP and port information to the socket */
    listen(sd,5);/*Listen for incoming coonections */
    len=sizeof(cliaddr);
    accept(sd,(struct sockaddr *)&cliaddr,&len);/*accept the incoming connections*/
    return 0;
}

Program in GNU/LINUx to find the termination status of child process using wait system call and WIFEXITED and WIFSIGNLED MACROS

Image

/*download link for the program:http://www.slideshare.net/hackintoshrao/childexittest*/
/* The wait systems waits for the Child process to exit  if the child process is still under exection and
   wait call returns with the process ID of the exited child process and it stores the childs
   exit status in the argument passed to it

   pid_t wait(int *status);

   But there are 2 different ways by which a child process can exit
    1)  Normal Termination
       -This happens when the child process calls exit() or return
    2)  Abnormal termination
       -this happens when the child process is terminated by by an SIGNAL
          *when child calls abort system call , it will be killed ny ABORT signal no 6
          *when child tries to divide a number by 0 , it will be killed by signal no 8
    but the status obtained by the waitpid system call doesnt give an idea about whether the
    child process terminated normally or abnormally
    to find it out we can use these 2 macros defined in <sys/wait.h> and stdlib.h>
     -if the process has terminated nomrally we can find out the exit status ising these macros
     -if the process had terminated abnormally by an Signal then we can find out the Signal
      number of the signal which killed the child process

      the status obtained by wait system call has to be passed as an argement to these macros
      these macros are

      1)WIFEXITED(status)
Description:
 Returns True if status was returned for a child that terminated normally. In this case, we can
 execute WEXITSTATUS(status) to fetch the value that the child passed to exit, _exit,or _Exit.

      2)WIFSIGNALED(status)
 Returns True if status was returned for a child that terminated abnormally, by receipt of a signal
 that it didn’t catch. In this case, we can execute WTERMSIG(status)

*/
#define err_sys(msg) write(1,msg,50)
#include <stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include <sys/wait.h>
#include<sys/types.h>

void Info_on_termination_of_child(int status)
{
if (WIFEXITED(status))
 printf(“normal termination, exit status = %d\n”,WEXITSTATUS(status));

else if (WIFSIGNALED(status))

   printf(“abnormal termination, signal number = %d\n”,WTERMSIG(status));

}

int main(void)
{
pid_t pid;
int status;

if ((pid = fork()) < 0)//creating a child
 err_sys(“fork error”);
else if (pid == 0) /* child process*/
 exit(7); /*child process exiting normally ,only parent left*/
if (wait(&status) != pid) /*parent waiting for child */
 err_sys(“wait error”);
Info_on_termination_of_child(status);/*calling the function to get termination info*/

if ((pid = fork()) < 0)//forking to create a child again
 err_sys(“fork error”);
else if (pid == 0)/*child proces*/
 abort();/*Abnormal termintionof child process by ABORT signal only parent left*/
if (wait(&status) != pid)/*parent waiting for child to exit*/
err_sys(“wait error”);
Info_on_termination_of_child(status);/*calling the function to get termination info*/

if ((pid = fork()) < 0)
err_sys(“fork error”);
else if (pid == 0)
status =(status/0);
/* Division by Zero error generates SIGNAL.NO 8 which kills the child,only parent left*/
if (wait(&status) != pid) /*parent waiting for child process to end*/
 err_sys(“wait error”);
Info_on_termination_of_child(status);

exit(0);
}

ART OF APP BUILDING IN GNU/LINUX-2:Creating a window with username and time-date info(combining system programming and QT)

 

 

Image

 

Here it is the second post of the series “The Art of app building in GNU/LINUX”.One of the powerful feature of QTCREATOR is that it can interpret HTML codes,in short its HTML aware.This property is used to set the colour and font of the text.
this this post we’ll create a simple app for GNU/LINUX, A basic window displaying User name and the time-date info,here goes the tutorial , happy coding , happy hacking ..

Create a Empty Qt project as shown in the reference video .Add a C++ source file as illustrated in the video, write this piece of into it and run .

 

#include<QApplication>
#include<QLabel>
#include<time.h>
#include<unistd.h>
#include<pwd.h>
#include<string.h>
int main(int argc,char *argv[])
{
    char *buff,*buff1;
    buff=new char [100];
    buff1=new char [1000];
    time_t ticks;
    ticks=time(NULL);
    buff=ctime(&ticks);//buff now contains the date and time details
    struct passwd *pwd;
    pwd=getpwuid(getuid());//to get the usr name
    QApplication app(argc,argv);
    strcat(buff1,”<font color=blue><h2>HI “);
    strcat(buff1,pwd->pw_name);//obtaining the user name
    strcat(buff1,”</h2></font>”);

    strcat(buff1,buff);
/*only one string is supposed to be passed onto Qlabel to display it in the window
  so the strings are concatenated to form one big string with HTML code for font and
  colour with user name   and date-time information*/

    QLabel *label1=new QLabel(buff1);

    label1->showNormal();
    return app.exec();
}

Illustration of ‘isatty’ system call in GNU/LINUX

/* Hackintosh rao , codes for GNU/LINUX*/
/* int isatty(fd);
   fd is the file descriptor of a open file
   if the terminal is associated with the file whose Fd is given then ,
   isatty returns 1 , else
   it returns 0
   this system call is used to check whether any open file  with a file descriptor
   is connected to a terminal or not */
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
    if(!(isatty(fileno(stdout))))  /*fileno function returns the filedescriptor*/
    {
        write(2,”\n\nstandard o/p not associated with control terminal\n\n”,60);
        /*cannot write into standard output with File descriptor 1 , when the
        terminal is not associated with it , that is when standard o/p is redirected
        using ‘>’ operator when the program is invoked, so the o/p is written into
        standard error with file descriptor 2*/
        exit(0);
    }
    else

    {
        printf(“\no/p is associated with the control terminal\n\n”);
    }

    return 0;
}

System program in GNU/LINUX to get time of 5 countries using gmtime and time system call

//download link for the file:http://www.slideshare.net/hackintoshrao/countrytimec

/*HACKINTOSH RAO \M/ CODES FOR GNU LINUX
  SYSTEM CALLS USED:1)time_t time(time_t *);
                    2)struct tm *gmtime(time_t *);
  DESCRIPTION:AFTER CALLING “time” system call the returned value of type time_t(%ld) is stored first;
              then the same address of the same value is to be sent to “gmtime” system call;
              gmtime returns a pointer to the built in structure tm;
              then the pointer is used to access the members of the structure which will be filled with
              the information about the time , date ,day , year etc……….
              In this program just fetching the time and year using the pointer to the structure is illustrated
              “gmtime” returns time in GMT and function timeconversion is used to change it to time of a given country*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<time.h>
void timeconversion(int *hour,int *min,int diff_hour,int diff_min);
/* timeconversion function is used to convert GMT to time of a given country using the difference from GMT ex:INDIA +5.30 GMT*/
void align(void);
int main()
{
    time_t time_in_sec;/*built in data type to store very large numbers*/
    int hour,min,choice,diff_hour,diff_min;
    struct tm *timestructure;/*built in structure with members which fill the details like day,time and so on*/

  for(;;)
  {
    time_in_sec=time(&time_in_sec);
    timestructure=gmtime(&time_in_sec);
    hour=timestructure->tm_hour;
    min=timestructure->tm_min;
    printf(“\n\t1.GMT\n\t2.Indian Standard Time\n\t3.WASHINGTON D.C(U.S.A)\n\t4.LONDON U.K\n\t5.U.A.E\n\t6.AUSTRALIA\n\t7.EXIT\n”);
    printf(“Enter 1 for GMT or Choose the country: “);
    scanf(“%d”,&choice);
    switch(choice)
    {

        case 2:diff_hour=5;//IST is +5.30 hours ahead of GMT
               diff_min=30;
               timeconversion(&hour,&min,diff_hour,diff_min);

               align();
               printf(“Indian standard Time: %02d:%02d:%02d “,hour,min,timestructure->tm_sec);
               align();
               break ;
        case 1:align();
                printf(“GMT: %02d:%02d:%02d “,timestructure->tm_hour,timestructure->tm_min,timestructure->tm_sec);
                align();
                break;
        case 3:diff_hour=-5;//time in USA is +5.30 hours ahead of GMT
               diff_min=0;
               timeconversion(&hour,&min,diff_hour,diff_min);

               align();
               printf(“WASHINGTON D.C U.S.A: %02d:%02d:%02d “,hour,min,timestructure->tm_sec);
               align();
               break ;
        case 4:diff_hour=0;//IST is +5.30 hours ahead of GMT
               diff_min=0;
               timeconversion(&hour,&min,diff_hour,diff_min);

               align();
               printf(“UK: %02d:%02d:%02d “,hour,min,timestructure->tm_sec);
               align();
               break ;
        case 5:diff_hour=4;//IST is +5.30 hours ahead of GMT
               diff_min=0;
               timeconversion(&hour,&min,diff_hour,diff_min);

               align();
               printf(“UAE: %02d:%02d:%02d “,hour,min,timestructure->tm_sec);
               align();
               break ;
        case 6:diff_hour=11;//IST is +5.30 hours ahead of GMT
               diff_min=0;
               timeconversion(&hour,&min,diff_hour,diff_min);

               align();
               printf(“MELBOURNE,AUSTRALIA: %02d:%02d:%02d “,hour,min,timestructure->tm_sec);
               align();
               break ;
        case 7:exit(0);

        default:align();
                printf(“SELECT THE WRIGHT OPTION”);
                align();

    }
  }
}
void timeconversion(int *hour,int *min,int diff_hour,int diff_min)
{

               *hour=(*hour+diff_hour)%24;/*so a simple math to convert GMT to time of a given country*/
               *min=*min+diff_min;
               if((*min)>=60)
              {
                    *hour=(*hour+1)%24;
                    *min=*min-60;

              }

}
void align()//function just to get the alignments right
{
    printf(“\n\n*************************************************************************\n\n”);
}
Image