Tuesday, December 27, 2011

Java program that illustrates runtime polymorphism


// AIM : Java program that illustrates runtime polymorphism

import java.io.*;

abstract class animal
{
        //abstract method
        public abstract void move();
}
class man extends animal
{
        public void move()
        {
                System.out.println("Walks on his two legs..");
        }
}
class horse extends man
{
        public void move()
        {
                System.out.println("Runs on it's 4 legs..");
        }
}
class crocodile extends horse
{
        public void move()
        {
                System.out.println("Crawls on its belly..");
        }
}



class  poly
{
        public static void main(String[] args)
{
                System.out.print("\nRuntime polymorphism\n\n");
                animal a;
                a=new man();
                a.move(); //behaviour changed as man
                a=new crocodile();
                a.move(); //behaviour changed as crocodile
                a=new horse();
                a.move(); //behaviour changed as horse
}
}




WAJProgram to multiply two matrix elements if compatible and find transpose the matrix elements .


// AIM : program to multiply two matrix elements if compatible
//       and find transpose the matrix elements .

import java.io.*;

class  matmul
{
public static void main(String[] args) throws IOException
{
                int mat1[][]={{1,2,3},{4,5,6},{7,8,9}};
int mat2[][]={{1,2,3},{4,5,6},{7,8,9}};
                int mat3[][],tmat[][],i,j,k;
mat3=new int[3][3];
                tmat=new int[3][3];
                //comaptibility or length test
                if(mat1.length!=mat2.length)
                {
                System.out.println("Matrix not compatible...");
                System.exit(0);
                }
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
for(k=0;k<=2;k++)
{
mat3[i][j]+=mat1[i][k]*mat2[k][j];
}
}
}

System.out.println("After Matrix Multiplicatin......");

for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
System.out.print(mat3[i][j]+"\t");
}
System.out.print("\n");
}

                /* transpose of matrix */
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
                        tmat[i][j]=mat3[j][i];
}
}
                System.out.println("After Transpose..");

for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
                        System.out.print(tmat[i][j]+"\t");
}
System.out.print("\n");
}

}
}




Thursday, December 15, 2011

Write a Java Program to read 5 strings and sort the strings in ascending order


// AIM :  Write a Java Program to read 5 strings and sort the strings in ascending order 


import java.io.*;


class strsort
{
       public static void main(String arg[]) throws IOException
        {

int i,j,len;
String s[]=new String[5],swp;

DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter  5 strings ?");
for(i=0;i<=4;i++)
s[i]=in.readLine();


for(i=0;i<=3;i++)
{
for(j=i+1;j<=4;j++)
if(s[i].compareTo(s[j])>0)
{
swp=s[i];
s[i]=s[j];
s[j]=swp;
}

}
System.out.println("After sort....");

for(i=0;i<=4;i++)
  System.out.println(s[i]);


        }
}

Write a Java Program to test the given string is palindrome or not


//AIM:  Write a Java Program to test the given string is palindrome or not

import java.io.*;

class pal
{
       public static void main(String arg[]) throws IOException
        {

int i,j,len;
String s;

DataInputStream in=new DataInputStream(System.in);

System.out.print("Enter a string ?");
s=in.readLine();
len=s.length();

                        System.out.println("Len="+len);
                       
                        for(i=0,j=len-1;i<(len/2);i++,j--)
{
if(s.charAt(i)!=s.charAt(j))
break;
}

                        if(i==(len/2))
  System.out.println("Pal string");
else
  System.out.println("Not a Pal string");

        }
}

Friday, December 9, 2011

Write a java program to generate fibonacci nos up to the nth value


Aim : Write a java program to generate fibonacci nos up to the nth value

//importing io classes
import java.io.*;



class  Fibonacci
{
public static void main(String[] args) throws IOException
{
DataInputStream in=new DataInputStream(System.in);
String s;
int a=1,b=1,c=a+b;
int n;

System.out.print("Enter nth value?");
s=in.readLine();
n=Integer.parseInt(s);
                System.out.print(a+","+b+",");
while(c<=n)
{
                        System.out.print(c+",");
a=b;
b=c;
c=a+b;
}
}
}

Write a java Program to print Fibonacci up to n (10) terms.


Aim : Write a java Program to print Fibonacci up to  n (10) terms.

//importing io classes
import java.io.*;


class  Fibonacci_rec
{
public int fibo(int n)
{
if (n == 1)
return 1;
else if (n == 2)
return 1;
else
return fibo(n-1) + fibo(n-2);
}
/*
This method will do exactly that, it will invoke the two previous versions of itself,
and those invoked will invoke their previous selves and so on until one of them reaches
f(2) or f(1). It's easy to use this method in a loop to print out many Fibonacci numbers:
*/


public static void main(String[] args)
{

Fibonacci_rec f=new Fibonacci_rec();
for (int i=1; i<10; i++)
System.out.println(f.fibo(i));


}
}

Thursday, October 13, 2011

RVS_SOLUTIONS: JNTU links for students

RVS_SOLUTIONS: JNTU links for students: Procedure to apply for Original Degree & Migration Certificate http://forum.jntuworld.com/showthread.php?5130-Procedure-to-apply-for-Origin...

JNTU links for students

Procedure to apply for Original Degree & Migration Certificate
http://forum.jntuworld.com/showthread.php?5130-Procedure-to-apply-for-Original-Degree-amp-Migration-Certificate&p=16109

Procedure to correct Names in Marks lists
http://forum.jntuworld.com/showthread.php?5132-Procedure-to-correct-Names-in-Marks-lists


Procedure to get Duplicate Marks Memo (In case if they are lost or anyother reason)
http://forum.jntuworld.com/showthread.php?5133-Procedure-to-get-Duplicate-Marks-Memo-%28In-case-if-they-are-lost-or-anyother-reason%29&p=16112

Procedure to apply Transcripts (Certified Duplicate Marks Memos)

http://forum.jntuworld.com/showthread.php?5134-Procedure-to-apply-Transcripts-%28Certified-Duplicate-Marks-Memos%29&p=16113

Job Links For Fresh Btech Engineers

Friday, September 23, 2011

UDP simple clent/server to transfer a file

# include "unp.h"

/* UDP echo server dg_echo function to transfer a file : */

void dg_echo(int sockfd,SA*pcliaddr,socklen_t clilen)
{
FILE*f;
int n,i=0,ch;
socklen_t len;
char mesg[MAXLINE];
for(;;){
len=clilen;
n=Recvfrom(sockfd,mesg,MAXLINE,0,pcliaddr,&len);
printf(" sending data.");
f=fopen("myfile","r");
while((ch=getc(f))!=-1)
mesg[i++]=ch;
mesg[i]=0; //init null
Sendto(sockfd,mesg,i,0,pcliaddr,len);
}
}


/*UDP echo server main function:*/


#include"unp.h"
int main(int argc,char **argv[])
{
int sockfd;
struct sockaddr_in servaddr,cliaddr;
sockfd=socket(AF_INET,SOCK_DGRAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(SERV_PORT);
Bind(sockfd,(SA*)&servaddr,sizeof(servaddr));
dg_echo(sockfd,(SA*)&cliaddr,sizeof(cliaddr));
}

# include "unp.h"

/* UDP ECHO Client: dg_cli function  to transfer the file*/

void dg_cli(FILE *fp,int sockfd,const SA* pservaddr,socklen_t servlen)
{
int n;
char sendline[MAXLINE], recvline[MAXLINE+1];

while ( Fgets(sendline,MAXLINE,fp)!=NULL)
{
sendto(sockfd, sendline, strlen(sendline), 0, pservaddr,servlen);
n= Recvfrom(sockfd,recvline, MAXLINE,0,NULL,NULL);
recvline[n]=0;
Fputs(recvline, stdout);
}
}



/* UDP client main function: */

int main(int argc, char **argv)

{

int sockfd;
struct sockaddr_in servaddr;
if(argc!=2)
err_quit("usage : udpcli <Ipaddress>");
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family= AF_INET;
servaddr.sin_port = htons(SERV_PORT);
Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
sockfd = Socket(AF_INET, SOCK_DGRAM, 0);
dg_cli(stdin, sockfd, (SA*) &servaddr, sizeof(servaddr));
exit(0);
}

Tuesday, September 6, 2011

Simple UDP clent / server program to transfer a file

/* UDP server program to transfer the file */
# include "unp.h"

/* UDP echo server dg_echo function: */

void dg_echo(int sockfd,SA*pcliaddr,socklen_t clilen)
{
FILE*f;
int n,i=0,ch;
socklen_t len;
char mesg[MAXLINE];
for(;;){
len=clilen;
n=Recvfrom(sockfd,mesg,MAXLINE,0,pcliaddr,&len);
printf(" sending data.");
f=fopen("myfile","r");
while((ch=getc(f))!=-1)
mesg[i++]=ch;
mesg[i]=0; //init null
Sendto(sockfd,mesg,i,0,pcliaddr,len);
}
}


/*UDP echo server main function:*/


#include"unp.h"
int main(int argc,char **argv[])
{
int sockfd;
struct sockaddr_in servaddr,cliaddr;
sockfd=socket(AF_INET,SOCK_DGRAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(SERV_PORT);
Bind(sockfd,(SA*)&servaddr,sizeof(servaddr));
dg_echo(sockfd,(SA*)&cliaddr,sizeof(cliaddr));
}




/* udp clent program  */
# include "unp.h"

/* UDP ECHO Client: dg_cli function*/

void dg_cli(FILE *fp,int sockfd,const SA* pservaddr,socklen_t servlen)
{
int n;
char sendline[MAXLINE], recvline[MAXLINE+1];

while ( Fgets(sendline,MAXLINE,fp)!=NULL)
{
sendto(sockfd, sendline, strlen(sendline), 0, pservaddr,servlen);
n= Recvfrom(sockfd,recvline, MAXLINE,0,NULL,NULL);
recvline[n]=0;
Fputs(recvline, stdout);
}
}



/* UDP client main function: */

int main(int argc, char **argv)

{

int sockfd;
struct sockaddr_in servaddr;
if(argc!=2)
err_quit("usage : udpcli <Ipaddress>");
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family= AF_INET;
servaddr.sin_port = htons(SERV_PORT);
Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
sockfd = Socket(AF_INET, SOCK_DGRAM, 0);
dg_cli(stdin, sockfd, (SA*) &servaddr, sizeof(servaddr));
exit(0);
}









Friday, September 2, 2011

Simple UDP clent/server to echo the string in reverse

/* udp simple server program to reverse a string */
# include "unp.h"

/* UDP echo server dg_echo function: */

void dg_echo(int sockfd,SA*pcliaddr,socklen_t clilen)
{
int n,i,j,swp;
socklen_t len;
char mesg[MAXLINE];
for(;;){
len=clilen;
n=Recvfrom(sockfd,mesg,MAXLINE,0,pcliaddr,&len);
printf("From Client : %s reversing ..",mesg);
for(i=0,j=n-1;i<n/2;i++,j--)
{
swp=mesg[i];
mesg[i]=mesg[j];
mesg[j]=swp;
}
Sendto(sockfd,mesg,n,0,pcliaddr,len);
}
}


/*UDP echo server main function:*/


#include"unp.h"
int main(int argc,char **argv[])
{
int sockfd;
struct sockaddr_in servaddr,cliaddr;
sockfd=socket(AF_INET,SOCK_DGRAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(SERV_PORT);
Bind(sockfd,(SA*)&servaddr,sizeof(servaddr));
dg_echo(sockfd,(SA*)&cliaddr,sizeof(cliaddr));
}

/*=================================================*/
/*udp client program to reverse a string*/

# include "unp.h"

/* UDP ECHO Client: dg_cli function*/

void dg_cli(FILE *fp,int sockfd,const SA* pservaddr,socklen_t servlen)
{
int n;
char sendline[MAXLINE], recvline[MAXLINE+1];

while ( Fgets(sendline,MAXLINE,fp)!=NULL)
{
sendto(sockfd, sendline, strlen(sendline), 0, pservaddr,servlen);
n= Recvfrom(sockfd,recvline, MAXLINE,0,NULL,NULL);
recvline[n]=0;
Fputs(recvline, stdout);
}
}



/* UDP client main function: */

int main(int argc, char **argv)

{

int sockfd;
struct sockaddr_in servaddr;
if(argc!=2)
err_quit("usage : udpcli <Ipaddress>");
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family= AF_INET;
servaddr.sin_port = htons(SERV_PORT);
Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
sockfd = Socket(AF_INET, SOCK_DGRAM, 0);
dg_cli(stdin, sockfd, (SA*) &servaddr, sizeof(servaddr));
exit(0);
}

/* use wrapsock.c in compilation */





















Saturday, August 27, 2011

UDP client /server program to transfer a string in reverse


/* UDP server code  to reverse a string */

#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h> /* close() */
#include <string.h> /* memset() */

#define LOCAL_SERVER_PORT 1500
#define MAX_MSG 100

int main(int argc, char *argv[]) {
int l,x,y;
char swp;
int sd, rc, n, cliLen, flags;
struct sockaddr_in cliAddr, servAddr;
char msg[MAX_MSG];

/* socket creation */
sd=socket(AF_INET, SOCK_DGRAM, 0);
if(sd<0) {
printf("%s: cannot open socket \n",argv[0]);
exit(1);
}

/* bind local server port */
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(LOCAL_SERVER_PORT);
rc = bind (sd, (struct sockaddr *) &servAddr,sizeof(servAddr));
if(rc<0) {
printf("%s: cannot bind port number %d \n",
argv[0], LOCAL_SERVER_PORT);
exit(1);
}

printf("%s: waiting for data on port UDP %u\n",
argv[0],LOCAL_SERVER_PORT);


flags = 0;


/* server infinite loop */
while(1) {

/* init buffer */
memset(msg,0x0,MAX_MSG);

/* receive message */
cliLen = sizeof(cliAddr);
n = recvfrom(sd, msg, MAX_MSG, flags,
(struct sockaddr *) &cliAddr, &cliLen);

if(n<0) {
printf("%s: cannot receive data \n",argv[0]);
continue;
}

/*reversing string */
l=strlen(msg);

for(x=0,y=l-1;x<l/2;x++,y--)
{
swp=msg[x];
msg[x]=msg[y];
msg[y]=swp;
}
/* print received message */
printf("%s: from %s:UDP%u : %s \n",
argv[0],inet_ntoa(cliAddr.sin_addr),
ntohs(cliAddr.sin_port),msg);


sleep(1);
sendto(sd,msg,n,flags,(struct sockaddr *)&cliAddr,cliLen);


}/* end of server infinite loop */

return 0;

}



/* UDP client code  */


#include <stdlib.h> /* for exit() */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h> /* memset() */
#include <sys/time.h> /* select() */

#define REMOTE_SERVER_PORT 1500
#define MAX_MSG 100


#define SOCKET_ERROR -1

int isReadable(int sd,int * error,int timeOut) { // milliseconds
fd_set socketReadSet;
FD_ZERO(&socketReadSet);
FD_SET(sd,&socketReadSet);
struct timeval tv;
if (timeOut) {
tv.tv_sec = timeOut / 1000;
tv.tv_usec = (timeOut % 1000) * 1000;
} else {
tv.tv_sec = 0;
tv.tv_usec = 0;
} // if
if (select(sd+1,&socketReadSet,0,0,&tv) == SOCKET_ERROR) {
*error = 1;
return 0;
} // if
*error = 0;
return FD_ISSET(sd,&socketReadSet) != 0;
} /* isReadable */



int main(int argc, char *argv[]) {

int sd, rc, i, n, echoLen, flags, error, timeOut;
struct sockaddr_in cliAddr, remoteServAddr, echoServAddr;
struct hostent *h;
char msg[MAX_MSG];


/* check command line args */
if(argc<3) {
printf("usage : %s <server> <data1> ... <dataN> \n", argv[0]);
exit(1);
}

/* get server IP address (no check if input is IP address or DNS name */
h = gethostbyname(argv[1]);
if(h==NULL) {
printf("%s: unknown host '%s' \n", argv[0], argv[1]);
exit(1);
}

printf("%s: sending data to '%s' (IP : %s) \n", argv[0], h->h_name,
inet_ntoa(*(struct in_addr *)h->h_addr_list[0]));

remoteServAddr.sin_family = h->h_addrtype;
memcpy((char *) &remoteServAddr.sin_addr.s_addr,
h->h_addr_list[0], h->h_length);
remoteServAddr.sin_port = htons(REMOTE_SERVER_PORT);

/* socket creation */
sd = socket(AF_INET,SOCK_DGRAM,0);
if(sd<0) {
printf("%s: cannot open socket \n",argv[0]);
exit(1);
}

/* bind any port */
cliAddr.sin_family = AF_INET;
cliAddr.sin_addr.s_addr = htonl(INADDR_ANY);
cliAddr.sin_port = htons(0);

rc = bind(sd, (struct sockaddr *) &cliAddr, sizeof(cliAddr));
if(rc<0) {
printf("%s: cannot bind port\n", argv[0]);
exit(1);
}


flags = 0;

timeOut = 100; // ms


/* send data */
for(i=2;i<argc;i++) {
rc = sendto(sd, argv[i], strlen(argv[i])+1, flags,
(struct sockaddr *) &remoteServAddr,
sizeof(remoteServAddr));

if(rc<0) {
printf("%s: cannot send data %d \n",argv[0],i-1);
close(sd);
exit(1);
}


/* init buffer */
memset(msg,0x0,MAX_MSG);

while (!isReadable(sd,&error,timeOut)) printf(".");
printf("\n");

/* receive echoed message */
echoLen = sizeof(echoServAddr);
n = recvfrom(sd, msg, MAX_MSG, flags,
(struct sockaddr *) &echoServAddr, &echoLen);

if(n<0) {
printf("%s: cannot receive data \n",argv[0]);
continue;
}

/* print received message */
printf("%s: echo from %s:UDP%u : %s \n",
argv[0],inet_ntoa(echoServAddr.sin_addr),
ntohs(echoServAddr.sin_port),msg);



}

return 1;

}















Tuesday, August 23, 2011

Infosys Campus Connect Sample Test1 Dt: 20-08-2011


RNEC-ongole CSE dept

Model Test 1                                                                                                          Dt:20-08-11
Answr all , each carries 1 mark                                             Max Marks : 20 ,Time :30 min

1 .How many bits of address bus are required to address 1MB memory                                    [   ]
a) 12 bits  b) 20 bits   c) 25 bits  d) 24 bits     
           
2. During the fetch/decode cycle, the contents of PC  are transferred to                                   [   ]
            a) MAR                     b) MBR              c) IR            3) Cache

3. which one of the following is not true about the primary memory                                         [    ]
            a) Implemented in high speed devices located outside CPU                    b)Volatile                         
            c) Holds program contents currently being executed    d)Cheaper than secondary memory

4. What are the sequence of execution of an instruction                                                             [    ]
a)Analysis, Decode and Execute   b)Fetch, Decode and Execute
c)Transfer, Analysis and Execute  d)Decode, Analysis and Fetch

5.The process where the DMA controller directly access the memory system to obtain the data is known as                                                                                                                                       [    ]
            a)Data transfer    b)Data stealing      c)page stealing       d)cycle stealing

6.Which of the following algorithm design technique is used for binary search algorithm        [    ]
a)      Divide and Conquer b) Brute force  c) Greedy approach d)Heuristic based approach

7. Which of the following is NOT an essential property of an algorithm                                  [    ]
            a) Definiteness b) Concurrency  c) Finiteness                                    d) Effectiveness

8. Which of the following statement is False                                                                             [    ]      
a) Greedy approach always gives optimal solution
b) All the algorithms must have property of definiteness      
c) Computer science is study of computation             d)Brute force is just DOIT approach

9. Which of the following statement is Incorrect                                                                       [   ]
a)Flowchart is a graphical representation of an algorithm
b)Algorithm can be represented in the form of flowchart
c) Algorithm is a set of steps to accomplish a task and the set may contain infinite steps
d)An operating system logic in theory is not an algorithm

10. The avg. successful search time taken by binary search on a sorted array of 10 items is     [   ]
            a)2.6    b)2.8    c)2.9    d)3.3

11.The algorithm design technique primarly used in optimization problems is?                         [   ]
            a)Divide and Conquer                        b)Greedy         c)Dynamic programming        d)b&c 

12.Which of the following algorithm design technique uses the top down approach                 [   ]
            a)Divide and Conquer                        b)Greedy         c)Dynamic programming        d)Brute force 
______________________________________________________________________________
13. The following data structure is more efficient to store the large number of employees in the organization                                                                                                                                    [     ]
a) Array b) Stack c) Linked List  d) Linear list
14. Virtual memory size depends on                                                                                       [     ]
a) address lines    b) data bus  c) disc space       d)  a & c   

15. Context switch takes place when process                                                                         [     ]
            a) blocks          b)i/o interrupt occurs   c)terminates     d)all
16. Indicate which of the following transition not possible                                                     [     ]
(a) Run-Ready (b) Run-Blocked (c) Blocked-Run (d) Run-Terminate

17.  What is the disadvantage of non-preemptive scheduling                                                  [     ]
             a) Aging         b) Context switching              c) Thrashing    d) Monopoly

18. In an absolute loading scheme, which loader function is accomplished by assembler      [     ]
a) Reallocation b) Allocation    c) Linking     d) Both (a) and (b)
19.  Compaction technique is used to overcome the ________ problem                                  [     ]
a) Internal fragmentation b) External fragmentation c) deadlock d)  Starvation

20. What is the max. decimal number that can be accommodated in a byte.                            [     ]
a) 128                 b) 255                             c) 256                                       d) 512

21. What is the page fault for the following reference string using LRU algorithm. Assume no. of frames available are 5                                                                                                        [     ]
                                    2 3 5 2 1 3 4 6 4
            a) 6                 b) 5                             c) 4                                       d) 7

22. What is the average waiting time for FCFS for the following processes whose CPU times are given below                                                                                                                                 [     ]
     P1 8ms                         P2 5ms                             P3 6ms

            a) 7                 b) 9                             c) 12                                       d) 6

23. What is the page fault for the following reference string using LRU algorithm. Assume no. of frames available are 5                                                                                                       [     ]
                                     2 3 5 2 1 3 4 6 4

            a) 6                 b) 5                             c) 4                                       d) 7         
24. Belody anamoly problem occurs in ____ page replacement algorithm                               [     ]
   
            a) FIFO                 b) LRU                             c) MRU                                       d) LFU       
Key for Campus Connect Sample test Dt : 20-08-11
Q.No
Answer
1
b
2
a
3
d
4
b
5
d
6
a
7
b
8
a or c
9
c
10
d
11
c
12
a
13
a
14
a or d
15
d
16
c
17
d
18
d
19
b
20
b
21
a
22
a
23
Q repeated _ Cancelled
24
a

Valued Only for a3 Questions


Thursday, August 18, 2011

TCP clent/server to transfer a file

/* tcp client program */
#include "unp.h"
void
str_cli(FILE *fp, int sockfd)
{
char sendline[MAXLINE], recvline[MAXLINE];
while (Fgets(sendline, MAXLINE, fp) != NULL) {
Writen(sockfd, sendline, strlen(sendline));
if (Readline(sockfd, recvline, MAXLINE) == 0)
err_quit("str_cli: server terminated prematurely");
Fputs(recvline, stdout);
}
}
int
main(int argc, char **argv)
{
int sockfd;
struct sockaddr_in servaddr;
if (argc != 2)
err_quit("usage: tcpcli <IPaddress>");
sockfd = Socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERV_PORT);
Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
Connect(sockfd, (SA *) &servaddr, sizeof(servaddr));
str_cli(stdin, sockfd); /* do it all */
exit(0);
}

/* tcp server program */
/* TCP server to transfer the file */
 
#include "unp.h"
void
str_echo(int sockfd)
{
long arg1, arg2;
ssize_t n;
char line[MAXLINE];
char fname[100];
char ch;
FILE*f;

int i=0;
for ( ; ; ) {
if ( (n = Readline(sockfd, line, MAXLINE)) == 0)
return; /* connection closed by other end */
n = strlen(line);
printf("\nReq From Client for file : %s",line);

strcpy(fname,line);
f=fopen("myfile","r");
while((ch=getc(f))!=EOF)
{
line[i++]=ch;
}
printf("\n....%d",i);
fclose(f);
Writen(sockfd, line, n);
}
}
int
main(int argc, char **argv)
{
int listenfd, connfd;
pid_t childpid;
socklen_t clilen;
struct sockaddr_in cliaddr, servaddr;
listenfd = Socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));
Listen(listenfd, LISTENQ);
printf("Server Running on Port %d\n", SERV_PORT);
for ( ; ; ) {
clilen = sizeof(cliaddr);
connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);
if ( (childpid = Fork()) == 0) { /* child process */
Close(listenfd); /* close listening socket */
str_echo(connfd); /* process the request */
exit(0);
}
Close(connfd); /* parent closes connected socket */
}
}

Wednesday, August 3, 2011

Semaphore /Shared memory simple example


/*
Shared memory is perhaps the most powerful of the SysV IPC methods, and it is the easiest to implement. As the name implies, a block of memory is shared between processes. Listing 7 shows a program that calls fork(2) to split itself into a parent process and a child process, communicating between the two using a shared memory segment.
A program illustrating the use of shared memory
The following program shows the contents of Filename : sema_simple.c
*/

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
int main(void) {
pid_t pid;
int *shared; /* pointer to the shm */
int shmid;
shmid = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666);
if (fork() == 0) { /* Child */
/* Attach to shared memory and print the pointer */
shared = shmat(shmid, (void *) 0, 0);
printf("Child pointer %u\n", shared);
*shared=1;
printf("Child value=%d\n", *shared);
sleep(2);
printf("Child value=%d\n", *shared);
} else { /* Parent */
/* Attach to shared memory and print the pointer */
shared = shmat(shmid, (void *) 0, 0);
printf("Parent pointer %u\n", shared);
printf("Parent value=%d\n", *shared);
sleep(1);
*shared=42;
printf("Parent value=%d\n", *shared);
sleep(5);
shmctl(shmid, IPC_RMID, 0);
}
}

TCP concurrent client/server program to echo a string in reverse

/* TCP concurrent server program to echo the string in reverse file : tcp_echo_ser.c */
#include "unp.h"
# include <string.h>
void
str_echo(int sockfd)
{
long arg1, arg2;
ssize_t n;
char line[MAXLINE];
char c,*s;
int i,j;
for ( ; ; ) {
if ( (n = Readline(sockfd, line, MAXLINE)) == 0)
return; /* connection closed by other end */

n = strlen(line);

s=line;
printf("\nReq From Client : %s",line);
for(i=0,j=n-1;i<n/2;i++,j--)
{
c=s[i];
s[i]=s[j];
s[j]=c;
}



Writen(sockfd, line, n);
}
}

int
main(int argc, char **argv)
{
int listenfd, connfd;
pid_t childpid;
socklen_t clilen;
struct sockaddr_in cliaddr, servaddr;

listenfd = Socket(AF_INET, SOCK_STREAM, 0);

bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);

Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

Listen(listenfd, LISTENQ);

printf("Server Running on Port %d\n", SERV_PORT);
for ( ; ; ) {
clilen = sizeof(cliaddr);
connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);

if ( (childpid = Fork()) == 0) { /* child process */
Close(listenfd); /* close listening socket */
str_echo(connfd); /* process the request */
exit(0);
}
Close(connfd); /* parent closes connected socket */
}
}

/*###########################################################################*/

  /* TCP concurrent client  program to echo the string in reverse file : tcp_echo_clnt.c */
#include "unp.h"
# include <string.h>
void
str_echo(int sockfd)
{
long arg1, arg2;
ssize_t n;
char line[MAXLINE];
char c,*s;
int i,j;
for ( ; ; ) {
if ( (n = Readline(sockfd, line, MAXLINE)) == 0)
return; /* connection closed by other end */

n = strlen(line);

s=line;
printf("\nReq From Client : %s",line);
for(i=0,j=n-1;i<n/2;i++,j--)
{
c=s[i];
s[i]=s[j];
s[j]=c;
}



Writen(sockfd, line, n);
}
}

int
main(int argc, char **argv)
{
int listenfd, connfd;
pid_t childpid;
socklen_t clilen;
struct sockaddr_in cliaddr, servaddr;

listenfd = Socket(AF_INET, SOCK_STREAM, 0);

bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);

Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

Listen(listenfd, LISTENQ);

printf("Server Running on Port %d\n", SERV_PORT);
for ( ; ; ) {
clilen = sizeof(cliaddr);
connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);

if ( (childpid = Fork()) == 0) { /* child process */
Close(listenfd); /* close listening socket */
str_echo(connfd); /* process the request */
exit(0);
}
Close(connfd); /* parent closes connected socket */
}
}