Wednesday, June 17, 2009

Transfer Control Protocol (TCP)

Posted by Sarjukottapuram

TRANSFER CONTROL PROTOCOL(TCP)


Server

Algorithm

The activity involved in a tcp server are..........
1.Create a socket.
2.Bind it to the operating system.
3.Listen over it.
4.Accept connections.
5.Read/Write processes.
6.Close the socket.

Program

/*Program to demonstrate the creation and usage of tcp socket.
* This module acts as the tcp server which listens to a socket and accepts connection.
* The server initially reads a message from the client and then writes a message to it.
* This module should be compiled using the command. 'c++ tcpserver.cpp' and execute './a.out'.*/

//inculsion.
#include
#include
#include
#include
#include
int main()
{

//variables to store the socket id.
int serversocket,clientsocket;

//variables to store the network host addresses.
sockaddr_in serveraddr,clientaddr;

//variable to store address length.
socklen_t len;
char message[50];

//creating a socket.
serversocket=socket(AF_INET,SOCK_STREAM,0);

//steps to include the host address
bzero((char*)&serveraddr,sizeof(serveraddr));
serveraddr.sin_family=AF_INET;
serveraddr.sin_port=htons(5030);
serveraddr.sin_addr.s_addr=INADDR_ANY;

//binding the socket to the operating system.
bind(serversocket,(sockaddr*)&serveraddr,sizeof(serveraddr));
bzero((char*)&clientaddr,sizeof(clientaddr));
len=sizeof(clientaddr);

//listening over the socket.
listen(serversocket,5);
printf("\nWaiting for client connectivity.\n");

//accepting the connection.
clientsocket=accept(serversocket,(sockaddr*)&clientaddr,&len);
printf("\nClient connectivity received.\n");
printf("\nReading message from the client.\n");

//reading activity.
read(clientsocket,message,sizeof(message));
printf("\nThe client has send:\t%s\n",message);
printf("\nSending message to the client.\n");

//writing activity.
write(clientsocket,"YOUR MESSAGE RECEIVED.",sizeof("YOUR MESSAGE RECEIVED."));
close(clientsocket);
close(serversocket);
}
Output

Client

Algorithm

The different processes involved in a udp client process are........
1.Create a datagram socket.
2.Receive/Send message to the server.
3.Close the socket.

Program
/* Program to demonstrate the creation and usage of datagram sockets.
* This module acts as a udp client which sends and receives messages from a udp server.
* This module should be compiled into different folder using the command 'c++
udpclient.cpp -o b' and execute using './b'
* For execution the 'udpserver' module should be executed first then this module.

//inculsion.
#include
#include
#include
#include
#include
int main()
{

//variable to store the socket_id.
int clientsocket;

//variable to store the address.
sockaddr_in serveraddr;

//variableto store the address length.
socklen_t len;

//variable to store the network byte order address.
hostent *server;
char message[50];

//socket creation.
clientsocket=socket(AF_INET,SOCK_DGRAM,0);

//steps involved in the server address creation.
bzero((char*)&serveraddr,sizeof(serveraddr));
len=sizeof(serveraddr);
serveraddr.sin_family=AF_INET;
serveraddr.sin_port=htons(5015);
server=gethostbyname("127.0.0.1");
bcopy((char*)server->h_addr,(char*)&serveraddr.sin_addr.s_addr,sizeof(server->h_addr));
printf("\nPRESS ENTER TO START THE CONNECTION PROCESS.\n");
fgets(message,2,stdin);
printf("\nSending message for server connection\n");

//sending message.
sendto(clientsocket,"HI I AM CLIENT...",sizeof("HI I AM CLIENT...."),0,(sockaddr*)&serveraddr,sizeof(serveraddr));
printf("\nReceiving message from server.\n");

//receiving messages.
recvfrom(clientsocket,message,sizeof(message),0,(sockaddr*)&serveraddr,&len);
printf("\nMessage received:\t%s\n",message);
close(clientsocket);
}

Output

Socket Programming

Posted by Sarjukottapuram

SOCKET PROGRAMMING

Theory

Sockets provide point-to-point, two-way communication between two processes. Sockets are very versatile and are a basic component of interprocess and intersystem communication. A socket is an endpoint of communication to which a name can be bound. It has a type and one or more associated processes.
Sockets exist in communication domains. A socket domain is an abstraction that provides an addressing structure and a set of protocols. Sockets connect only with sockets in the same domain. Twenty three socket domains are identified (see ), of which only the UNIX and Internet domains are normally used Solaris 2.x Sockets can be used to communicate between processes on a single system, like other forms of IPC.
The UNIX domain provides a socket address space on a single system. UNIX domain sockets are named with UNIX paths. Sockets can also be used to communicate between processes on different systems. The socket address space between connected systems is called the Internet domain.
Internet domain communication uses the TCP/IP internet protocol suite.
Socket types define the communication properties visible to the application. Processes communicate only between sockets of the same type. There are five types of socket.
A stream socket
-- provides two-way, sequenced, reliable, and unduplicated flow of data with no record boundaries. A stream operates much like a telephone conversation. The socket type is SOCK_STREAM, which, in the Internet domain, uses Transmission Control Protocol (TCP).

A datagram socket
-- supports a two-way flow of messages. A on a datagram socket may receive messages in a different order from the sequence in which the messages were sent. Record boundaries in the data are preserved. Datagram sockets operate much like passing letters back and forth in the mail. The socket type is SOCK_DGRAM, which, in the Internet domain, uses User Datagram Protocol (UDP).
A sequential packet socket
-- provides a two-way, sequenced, reliable, connection, for datagrams of a fixed maximum length. The socket type is SOCK_SEQPACKET. No protocol for this type has been implemented for any protocol family.
A raw socket
provides access to the underlying communication protocols.

These sockets are usually datagram oriented, but their exact characteristics depend on the interface provided by the protocol.

Socket Creation and Naming

int socket(int domain, int type, int protocol) is called to create a socket in the specified domain and of the specified type. If a protocol is not specified, the system defaults to a protocol that supports the specified socket type. The socket handle (a descriptor) is returned. A remote process has no way to identify a socket until an address is bound to it. Communicating processes connect through addresses. In the UNIX domain, a connection is usually composed of one or two path names. In the Internet domain, a connection is composed of local and remote addresses and local and remote ports. In most domains, connections must be unique.
int bind(int s, const struct sockaddr *name, int namelen) is called to bind a path or internet address to a socket. There are three different ways to call bind(), depending on the domain of the socket.

• For UNIX domain sockets with paths containing 14, or fewer characters, you can:
• #include
• ...
• bind (sd, (struct sockaddr *) &addr, length);
• If the path of a UNIX domain socket requires more characters, use:
• #include
• ...
• bind (sd, (struct sockaddr_un *) &addr, length);
• For Internet domain sockets, use
• #include
• ...
• bind (sd, (struct sockaddr_in *) &addr, length);
In the UNIX domain, binding a name creates a named socket in the file system. Use unlink() or rm () to remove the socket.

Connecting Stream Sockets

Connecting sockets is usually not symmetric. One process usually acts as a server and the other process is the client. The server binds its socket to a previously agreed path or address. It then blocks on the socket. For a SOCK_STREAM socket, the server calls int listen(int s, int backlog) , which specifies how many connection requests can be queued. A client initiates a connection to the server's socket by a call to int connect(int s, struct sockaddr *name, int namelen) . A UNIX domain call is like this:
struct sockaddr_un server;
...
connect (sd, (struct sockaddr_un *)&server, length);
while an Internet domain call would be:
struct sockaddr_in;
...
connect (sd, (struct sockaddr_in *)&server, length);
If the client's socket is unbound at the time of the connect call, the system automatically selects and binds a name to the socket. For a SOCK_STREAM socket, the server calls accept(3N) to complete the connection.
int accept(int s, struct sockaddr *addr, int *addrlen) returns a new socket descriptor which is valid only for the particular connection. A server can have multiple SOCK_STREAM connections active at one time.
Stream Data Transfer and Closing

Several functions to send and receive data from a SOCK_STREAM socket. These are write(), read(), int send(int s, const char *msg, int len, int flags), and int recv(int s, char *buf, int len, int flags). send() and recv() are very similar to read() and write(), but have some additional operational flags.

The flags parameter is formed from the bitwise OR of zero or more of the following:

MSG_OOB
-- Send "out-of-band" data on sockets that support this notion. The underlying protocol must also support "out-of-band" data. Only SOCK_STREAM sockets created in the AF_INET address family support out-of-band data.

MSG_DONTROUTE
-- The SO_DONTROUTE option is turned on for the duration of the operation. It is used only by diagnostic or routing pro- grams.

MSG_PEEK
-- "Peek" at the data present on the socket; the data is returned, but not consumed, so that a subsequent receive operation will see the same data.

A SOCK_STREAM socket is discarded by calling close().

Datagram sockets

A datagram socket does not require that a connection be established. Each message carries the destination address. If a particular local address is needed, a call to bind() must precede any data transfer. Data is sent through calls to sendto() or sendmsg(). The sendto() call is like a send() call with the destination address also specified. To receive datagram socket messages, call recvfrom() or recvmsg(). While recv() requires one buffer for the arriving data, recvfrom() requires two buffers, one for the incoming message and another to receive the source address.
Datagram sockets can also use connect() to connect the socket to a specified destination socket. When this is done, send() and recv() are used to send and receive data.

accept() and listen() are not used with datagram sockets.

Shared Memory

Posted by Sarjukottapuram

SHARED MEMORY

Theory

In computing, shared memory is a memory that may be simultaneously accessed by multiple programs with an intent to provide communication among them. Depending on context, programs may run on the same physical processor or on separate ones. Using memory for communication inside a single program, for example among its multiple threads, is generally not referred to as shared memory.
In computer software, shared memory is a method of inter-process communication (IPC), i.e. a way of exchanging data between programs running at the same time. One process will create an area in RAM which other processes can access.
Since both processes can access the shared memory area like regular working memory, this is a very fast way of communication (as opposed to other mechanisms of IPC such as named pipes, Unix sockets or CORBA). On the other hand, it is less powerful, as for example the communicating processes must be running on the same machine (whereas other IPC methods can use a computer network).
IPC by shared memory is mainly used on Unix systems.
POSIX provides a standardized API for using shared memory, POSIX Shared Memory. This uses the function shm_open from sys/mman.h.
Shared Memory is an efficeint means of passing data between programs. One program will create a memory portion which other processes (if permitted) can access.
In the Solaris 2.x operating system, the most efficient way to implement shared memory applications is to rely on the mmap() function and on the system's native virtual memory facility. Solaris 2.x also supports System V shared memory, which is another way to let multiple processes attach a segment of physical memory to their virtual address spaces. When write access is allowed for more than one process, an outside protocol or mechanism such as a semaphore can be used to prevent inconsistencies and collisions.
A process creates a shared memory segment using shmget()|. The original owner of a shared memory segment can assign ownership to another user with shmctl(). It can also revoke this assignment. Other processes with proper permission can perform various control functions on the shared memory segment using shmctl(). Once created, a shared segment can be attached to a process address space using shmat(). It can be detached using shmdt() (see shmop()). The attaching process must have the appropriate permissions for shmat(). Once attached, the process can read or write to the segment, as allowed by the permission requested in the attach operation. A shared segment can be attached multiple times by the same process. A shared memory segment is described by a control structure with a unique ID that points to an area of physical memory. The identifier of the segment is called the shmid. The structure definition for the shared memory segment control structures and prototypews can be found in .
Accessing a Shared Memory Segment
shmget() is used to obtain access to a shared memory segment. It is prottyped by:
int shmget(key_t key, size_t size, int shmflg);
The key argument is a access value associated with the semaphore ID. The size argument is the size in bytes of the requested shared memory. The shmflg argument specifies the initial access permissions and creation control flags.
When the call succeeds, it returns the shared memory segment ID. This call is also used to get the ID of an existing shared segment (from a process requesting sharing of some existing memory portion).
The following code illustrates shmget():

#include
#include
#include
...
key_t key; /* key to be passed to shmget() */
int shmflg; /* shmflg to be passed to shmget() */
int shmid; /* return value from shmget() */
int size; /* size to be passed to shmget() */
...
key = ...
size = ...
shmflg) = ...

if ((shmid = shmget (key, size, shmflg)) == -1) {
perror("shmget: shmget failed"); exit(1); } else {
(void) fprintf(stderr, "shmget: shmget returned %d\n", shmid);
exit(0);
}
...

Controlling a Shared Memory Segment

shmctl() is used to alter the permissions and other characteristics of a shared memory segment. It is prototyped as follows:
int shmctl(int shmid, int cmd, struct shmid_ds *buf);
The process must have an effective shmid of owner, creator or superuser to perform this command. The cmd argument is one of following control commands:
SHM_LOCK -- Lock the specified shared memory segment in memory. The process must have the effective ID of superuser to perform this command.
SHM_UNLOCK -- Unlock the shared memory segment. The process must have the effective ID of superuser to perform this command.
IPC_STAT-- Return the status information contained in the control structure and place it in the buffer pointed to by buf. The process must have read permission on the segment to perform this command.
IPC_SET-- Set the effective user and group identification and access permissions. The process must have an effective ID of owner, creator or superuser to perform this command.
IPC_RMID -- Remove the shared memory segment.
The buf is a sructure of type struct shmid_ds which is defined in

Program
Server

/*Program to demonstrate the use of shared memory in interprocess communication.
* This program acts as a server which waits for a message from the client process.
* The process is implemented using a shared memory space called 'shared_location'.
* The 'message' part of this space stores the message while the 'written' part is used to indicate whether the server has read the message or the client has written the message.(0->read,1->written).
* This module should be compiled and executed first.
* This module is compile using 'cc shmserver.c' and executed using './a.out'*/

//inculsion
#include
#include
#include
#include
#include
#include

//structure definition for acquiring a shared location.
struct shared_location
{
int written;
char message[30];
};
int main()
{
int shmid,running;
void *address;
struct shared_location * ptr;

//for getting a shared location
shmid=shmget((key_t)1234,sizeof(struct shared_location),0666|IPC_CREAT);

//optional if required for error checking.
if(shmid<=0) { printf("\nERROR:\tCannot allocate shared space.\n"); exit(0); } //attaching the shared location to this process.
address=shmat(shmid,(void *)0,0); //optional if required for error checking.
if(address==(void*)0) { printf("\nEROOR:\tShared location cannot be attached.\n"); } //type casting so as to convert the obyained location into our format.
ptr=(struct shared_location*)address; ptr->written=0;
strcpy(ptr->message,"Hi I am server.");
running=1;
while(running)
{
printf("\nWaiting for the client to enter the message.\n");

while(ptr->written==0)
{
}
if(ptr->written==1)
{
printf("The client has entered the message: %s\n",ptr->message);
}
ptr->written=0;
if(strcmp(ptr->message,"end")==0)
{
running=0;
}
}

//detaching the shared location.
shmdt(address);

//deleting the shared location.
shmctl(shmid,IPC_RMID,NULL);
}

Output

Client

Program

/* Program to demonstrate the use of shared memory in interprocess communication.
* This module acts as a client which sends messages to the server process.
* In this the message entered into the message part of the 'shared_location' structure and the 'written' field is set to 1.
* The remaining process is similar to that of the server process.
* This module can be compiled using 'cc shmclient.c -o b' and executed using './b'

//inculsion
#include
#include
#include
#include
#include
#include

//structure definition for the shared location.
struct shared_location
{
int written;
char message[30];
};

//the functions and other terms used have similar meanings to that used in the server module
 //but they don't bear any specific relationship.
int main()
{
int shmid,running;
void *address;
struct shared_location * ptr;
shmid=shmget((key_t)1234,sizeof(struct shared_location),0666|IPC_CREAT);
if(shmid<=0)
{
printf("\nERROR:\tCannot allocate shared memory.\n");
exit(0);
}
address=shmat(shmid,(void*)0,0);
if(address==(void*)0)
{
printf("\nERROR:\tCannot attach the shared location\n");
exit(0);
}
ptr=(struct shared_location*)address;
running=1;
while(running)
{
printf("\nWaiting for the server\n");
while(ptr->written==1)
{
}
printf("\nEnter your message.(type 'end' to exit)\n");
scanf("%s",ptr->message);
ptr->written=1;
if(strcmp(ptr->message,"end")==0)
{
running=0;
}
}
address=shmat(shmid,(void *)0,0);
shmdt(address);
}

Output

Pipes

Posted by Sarjukottapuram

PIPES - Linux in C


Theory

A pipe is a method of connecting the standard output of one process to the standard input of another. Pipes are the eldest of the IPC tools, having been around since the earliest incarnations of the UNIX operating system. They provide a method of one-way communications (hence the term half-duplex) between processes.
This feature is widely used, even on the UNIX command line (in the shell).
When a process creates a pipe, the kernel sets up two file descriptors for use by the pipe. One descriptor is used to allow a path of input into the pipe (write), while the other is used to obtain data from the pipe (read). At this point, the pipe is of little practical use, as the creating process can only use the pipe to communicate with itself.
While a pipe initially connects a process to itself, data traveling through the pipe moves through the kernel. Under Linux, in particular, pipes are actually represented internally with a valid inode. Of course, this inode resides within the kernel itself, and not within the bounds of any physical file system. This particular point will open up some pretty handy I/O doors for us, as we will see a bit later on.
At this point, the creating process typically forks a child process. Since a child process will inherit any open file descriptors from the parent, we now have the basis for multiprocess communication (between parent and child). It is at this stage, that a critical decision must be made. In which direction do we desire data to travel? Does the child process send information to the parent, or vice-versa? The two processes mutually agree on this issue, and proceed to ``close'' the end of the pipe that they are not concerned with.
To access a pipe directly, the same system calls that are used for low-level file I/O can be used (recall that pipes are actually represented internally as a valid inode).
To send data to the pipe, we use the write() system call, and to retrieve data from the pipe, we use the read() system call. Remember, low-level file I/O system calls work with file descriptors! However, keep in mind that certain system calls, such as lseek(), do not work with descriptors to pipes.
To create a simple pipe with C, we make use of the pipe() system call. It takes a single argument, which is an array of two integers, and if successful, the array will contain two new file descriptors to be used for the pipeline.

SYSTEM CALL: pipe();
PROTOTYPE: int pipe( int fd[2] );

RETURNS: 0 on success
-1 on error: errno = EMFILE (no free descriptors)

EMFILE (system file table is full)
EFAULT (fd array is not valid)

NOTES: fd[0] is set up for reading, fd[1] is set up for writing

The popen() function creates a pipe between the calling program and the command to be executed. The arguments topopen() are pointers to null-terminated strings. The com-mand argument consists of a shell command line. The modeargument is an I/O mode, either r for reading or w for writing. The value returned is a stream pointer such that one can write to the standard input of the command, if the I/Omode is w, by writing to the file stream and one can read from the standard output of the command, if the I/O mode is r, by reading from the file stream.

The pclose() function closes a stream opened by popen() by closing the pipe. It waits for the associated process to terminate and returns the termination status of the process running the command language interpreter. This is the value returned by waitpid(2).

SIMPLE PIPES OR LOWLEVEL PIPES

Program

/* Program to demonstrate the creation and use of simple/low level pipe.
* This program creates a pipe that connects the child process with its parent process.
* Here the child process writes 'REQUEST FROM CHILD PROCESS.' on to the pipe which is read by the parent process.
* The function 'fork()' is a system call used to create a child process.
* This module can be compiled using 'cc simplepipe.c' and executed using './a.out'

//inculsion
#include
#include
int main()
{

//array to store the pipe pointers returned by the pipe() function.
int pipe_pointer[2];

//variable to store the child process id.
pid_t child;
char message[50];

//creating a pipe
pipe(pipe_pointer);

//creating a child process.
child=fork();
if(child==0)
{
printf("\nThe child process is writing.\n");

//closing the read pointer.
close(pipe_pointer[0]);

//writing on to the pipe.
write(pipe_pointer[1],"REQUEST FROM CHILD PROCESS.",sizeof("REQUEST FROM CHILD PROCESS."));
}
else
{
printf("\nThe parent process is reading.\n");

//closing the write pointer.
close(pipe_pointer[1]);

//reading from the pipe.
read(pipe_pointer[0],message,sizeof(message));
printf("\nThe parent has read:\n\n** %s **\n",message);
}
close(pipe_pointer[0]);
close(pipe_pointer[1]);
}

Output

FORMATTED PIPE


/* Program to demonstrate the creation and use of formatted pipe.
* This program creates a formatted pipe which is connected to the system process denoted by the command 'CMD'.
* The pipe is established for reading and the read content is displayed.
* This module can be compiled using 'cc formattedpipe.c' and executed './a.out'.*/

//inculsion part
#include
#include
#define CMD "cal"
int main()
{
FILE *ptr;
char message[100];
char cmd[20];
strcpy(cmd,CMD);

//creating a formatted pipe.
ptr=popen(cmd,"r");
while( fgets(message,sizeof(message),ptr)!=NULL)
{
printf("%s",message);
}

//closing the pipe.
pclose(ptr);
}

Output

Tuesday, June 16, 2009

Computer Science - Seminar Report - Free Download

Posted by Sarjukottapuram

iSCSI(Small Computer System Interface)

Introduction

iSCSI(Small Computer System Interface), an Internet Protocol (IP)-based storage networking standard for linking data storage facilities, developed by the Internet Engineering Task Force (IETF). By carrying SCSI commands over IP networks, iSCSI is used to facilitate data transfers over intranets and to manage storage over long distances. The iSCSI protocol is among the key technologies expected to help bring about rapid development of the storage area network (SAN) market, by increasing the capabilities and performance of storage data transmission. Because of the ubiquity of IP networks, iSCSI can be used to transmit data over local area networks (LANs), wide area networks (WANs), or the Internet and can enable location-independent data storage and retrieval.
iSCSI builds on the two widely used protocols from the storage and networking worlds. From the storage side, iSCSI uses SCSI command set, the core storage commands used throughout all storage configurations. On the networking side, iSCSI uses IP and Ethernet, which are the basis for most corporate networks.
iSCSI is one of two main approaches to storage data transmission over IP networks; the other method, Fibre Channel over IP (FCIP), translates Fibre Channel control codes and data into IP packets for transmission between geographically distant Fibre Channel SANs. FCIP (also known as Fibre Channel tunneling or storage tunneling) can only be used in conjunction with Fibre Channel technology; in comparison, iSCSI can run over existing Ethernet networks. A number of vendors, including Cisco, IBM, and Nishan have introduced iSCSI-based products (such as switches and routers).

Download Full Seminar Report iSCSI

Monday, June 15, 2009

Computer Graphics - Moving Ball

Posted by Sarjukottapuram

/**** Author:Sarju


www.sarjus-elearning.blogspot.com****/

# include

# include

# include

# include



int x,y,maxx,maxy,i,j;



int main(void)

{

int gdriver = DETECT, gmode;

void *image;

unsigned int size;

char ch;

void fillBox(int,int);

int Row,Col;



// Initialize graphics drivers and mode.

initgraph(&gdriver,&gmode,"c:\\tc\\bgi");



// Draw a rectangle

// rectangle(x1,y1,x2,y2)

maxx=getmaxx(); // x2

maxy=getmaxy(); // y2

rectangle(10,10,maxx-10,maxy-10);



// Puts Pixel in the Rectangle.

fillBox(maxx,maxy);

x=y=70;

// Draw Circle and FillColor

setfillstyle(1,14);

circle(x,y,20);

floodfill(x,y,15);



// Creating the Image

size = imagesize(x,y,x+20,y+20);

image=malloc(size);

getimage(x-20,y-20,x+20,y+20,image);

x-=20;

y-=20;

// Will Displays till Any key is hit !!!...

while(!kbhit())

{

Row = x; Col = y;

putimage(x,y,image,XOR_PUT); // clears the Image from Screen

//x=random(maxx-70);

//y=random(maxy-70);

//fillBox(maxx,maxy);

x=x+10;

/* if(x<50)

x=50;

if(y<50)

y=50;*/

putimage(x,y,image,OR_PUT); // Puts the image on screen.

delay(50); // Waits for few Seconds.

if(x>540)

{

putimage(x,y,image,XOR_PUT);

Row = x; Col = y;

for(i=0;i<540;i++)

{

x=random(maxx-10);

y=random(maxy-10);

if(x>10 && y>10)

putpixel(x,y,14);

}

//putpixel(x,y,14);

x= Row;

y=Col;

x=10;

y=y+20;

putimage(x,y,image,XOR_PUT);

}

if(y>410)

{

putimage(x,y,image,XOR_PUT);

Row = x; Col = y;

fillBox(maxx,maxy);

x= Row;

y=Col;

x=10;

y=30;

putimage(x,y,image,XOR_PUT);

}

}

free(image); //Removes the image from the Screen.

closegraph(); // Closes the Graphics Mode.

return(0);

}



void fillBox(int maxx,int maxy)

{

cleardevice(); // Clears the Graphics Screen

maxx=getmaxx(); // x2

maxy=getmaxy(); // y2

rectangle(10,10,maxx-10,maxy-10);

for(i=0;i<8000;i++)

{

x=random(maxx-10);

y=random(maxy-10);

if(x>10 && y>10)

putpixel(x,y,14);

}

}

Computer Graphics - Animated Car

Posted by Sarjukottapuram

#include


/*** Author : Sarju S
http://www.sarjus-elearning.blogspot.com/
***/

#include
#include
#include
#include
void main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,"c:\\tc\\bgi");
int c=12;
setbkcolor(0);
//setlinestyle(0,1,2);
int t;
while(1)
{
settextstyle(2,0,5);
outtextxy(100,10,"Press L,H ,T,P");
outtextxy(100,30,"Press 1 for Quit");
as:
setcolor(13);
ellipse(380,127,20,152,130,35);
//////////////////////////////rear//////////////////////////
line(490,109,560,142);
line(560,142,569,142);

line(569,142,582,102);

line(582,102,620,92);

line(593,132,617,125);



line(617,124,627,96);

line(620,92,628,97);



line(472,86,602,96);

line(501,113,575,121);

line(443,77,475,80);



line(443,77,432,93);

line(475,80,472,85);

//setcolor(4);

line(593,132,593,137);

line(593,137,600,141);

line(600,141,600,185);

line(600,185,608,192);

line(608,192,608,234);

line(608,234,586,253);

line(586,253,577,248);



///////////////////////// mirror

line(263,112,363,127);

line(193,160,263,112);

line(193,160,220,170);

line(220,170,280,180);

line(280,180,320,185);

line(320,185,363,127);

////////////////////////////////sidemirror

line(340,194,460,169);

line(460,169,519,152);



ellipse(512,144,300,30,10,10);

ellipse(467,143,28,100,50,30);

line(510,128,521,138);

line(435,116,440,171);



// setcolor(4);

////////////////////////////////////////cont//

line(339,194,372,144);

// line(372,140,386,128);

ellipse(454,208,87,123,128,95);

line(372,144,384,128);

int b,x,y;

////////////////////////lower

line(365,298,524,264);

line(365,298,330,310);

line(330,310,323,310);





///////////////////////////////bumper

ellipse(162,221,135,190,90,40);

line(96,193,140,174);

line(140,174,160,168);

line(160,168,192,161);



//////////////////////front

ellipse(75,246,95,190,18,18);

line(57,251,57,286);

//setcolor(4);

ellipse(181,178,232,263,200,137);

ellipse(195,180,256,286,200,137);





ellipse(191,171,228,247,200,100);

ellipse(231,198,234,275,200,80);



//setcolor(9);

//ellipse(195,170,256,286,200,137);

//setcolor(12);



ellipse(196,167,228,246,200,90);

ellipse(231,184,234,276,200,80);





ellipse(191,200,228,246,200,90);

ellipse(228,218,234,276,200,80);



ellipse(258,268,180,220,200,40);

ellipse(178,296,244,355,16,10);



ellipse(238,249,227,250,200,60);





/////////////wheel1

ellipse(302,281,320,77,26,45);

ellipse(290,277,65,162,40,45);

ellipse(278,288,144,212,31,45);



/////////////wheel2

//setcolor(5);

ellipse(302+260,229,328,87,26,45);

ellipse(290+280-7,277-50+2,90,162,40,45);

ellipse(278+270,288-50,144,215,27,45);

b=0;

int v=0;



/////////

ellipse(302+250+v,227+b,295,90,29,41);

ellipse(302+234+v,231+b,245,306,50,40);

//setlinestyle(3,0,3);

ellipse(302+248+v,229+b,0,360,21,30);



ellipse(302+247+v,229+b,0,360,8,10);

setfillstyle(6,11);

//floodfill(302+248+v,230+b,13);

//line(546,201,546,257);

//line(554,201,554,257);

//setcolor(4);



line(546+v,201+b,546+v,220+b);

line(551+v,201+b-2,551+v,220+b);



line(546+v,238+b,546+v,257+b);

line(551+v,238+b+2,551+v,257+b+2);





line(530+v,225+b,541+v,225+b);

line(530+v,230+b,541+v,230);



line(557+v,225+b,570+v,225+b);

line(557+v,230+b,570+v,230+b);







line(563+v,206+b,552+v,222+b);

line(534+v,246+b,543+v,232+b);



line(566+v,210+b,556+v,223+b);

line(536+v,250+b,544+v,238+b);



line(536+v,207+b,546+v,222+b);

line(532+v,213+b,542+v,224+b);



line(556+v,235+b,566+v,247+b);

line(551+v,237+b,563+v,253+b);







////////////////////////////////////////////////////

v=-260;

b=56;

ellipse(302+233+v,221+b,260,60,49,51);

//ellipse(302+234+v,231+b,245,306,50,40);

//setlinestyle(3,0,3);

ellipse(302+243+v,224+b,0,360,28,35);

// line(249,328,269,328);

ellipse(300+245+v,223+b,0,360,10,12);



ellipse(285+249+v,239+b,210,260,30,33);

//floodfill(285+258+v,230+b,12);

b=45;

v=v-4;

line(546+v,201+b,546+v,220+b+2);

line(551+v,201+b,551+v,220+b+2);

b=b+8;

line(546+v,238+b,546+v,257+b+4);

line(551+v,238+b,551+v,257+b+4);

v=v-2;

line(530+v-6,225+b,541+v,225+b);

line(530+v-6,230+b,541+v,230+b);

v=v+5;

line(557+v,225+b,570+v+3,225+b);

line(557+v-1,230+b,570+v+3,230+b);





b=b-5;

v=v-5;

line(565+v+3,206+b,552+v+4,222+b-2);

b=b+15;



line(534+v,246+b,543+v+3,232+b-5);

b=b-10;

line(566+v+7,210+b-5,556+v+4,220+b);

line(536+v-5,250+b,544+v-2,238+b-4);





line(536+v,207+b-8,545+v,222+b-5);

line(531+v,212+b-8,542+v,224+b-2);



line(556+v,235+b,566+v+3,247+b+5);

line(551+v,237+b,563+v+2,253+b+3);



///////////////////lights

ellipse(199,250,144,345,18,8);

line(185,245,206,230);

//setcolor(4);

ellipse(223,234,340,110,8,5);

line(230,237,217,252);

line(206,230,220,229);

//setfillstyle(1,4);



//floodfill(200,240,12);



/////////////////////////////////////

line(90,223,152,236);

line(152,236,137,254);

line(90,223,90,242);



//setfillstyle(10,9);

//floodfill(91,230,14);

ellipse(240,270,104,136,100,60);

ellipse(185,237,120,160,100,60);

ellipse(80,221,357,134,10,10);



line(152,236,168,228);

///////////////////////////////////////////////

line(435,116,440,171);

//////////////////////////////////////////hp

//line(134,185,220,210);

line(134,185,196,160);

line(214,212,318,185);

/////////////////////////////////////////////////light



//setcolor(14);

ellipse(166,247,99,330,8,8);

ellipse(171,243,310,129,7,7);

putpixel(174,250,13);

putpixel(173,251,13);

putpixel(164,239,13);

putpixel(165,238,13);



/////////////////////////////////////////road/////////////////////

setcolor(13);

line(1,430,639,300);

line(1,445,639,315);



line(1,210,93,194);

line(1,195,194,158);



//line(1,170,639,71);

//line(1,170,229,135);

line(520,90,639,71);

line(478,86,639,56);



int c=0;



line(10,194+c,10,208+c);

line(40,189+c,40,204+c);

line(70,183+c,70,198+c);

line(100,176+c,100,190+c);

line(130,170+c,130,177+c);

line(160,166+c,160,168+c);

line(190,160+c,190,161+c);



line(190+330,78+c,190+330,89+c);



line(190+360,72+c,190+360,85+c);

line(190+390,67+c,190+390,81+c);

line(190+420,62+c,190+420,76+c);

line(190+449,57+c,190+449,71+c);







c=236;



line(10,192+c,10,208+c);

line(40,189+c-2,40,204+c-3);

line(70,183+c-3,70,198+c-3);

line(100,176+c-2,100,190+c-2);

line(130,170+c-2,130,177+c+5);

line(160,166+c-3,160,168+c+8);

line(190,160+c-4,190,161+c+9);



line(190+30,156+c-5,190+30,170+c-5);





line(190+30+30,156+c-12,190+30+30,170+c-12);



line(190+90,156+c-18,190+90,170+c-17);



line(190+120,156+c-25,190+120,170+c-25);



line(190+150,156+c-30,190+150,170+c-30);



line(190+180,156+c-37,190+180,170+c-36);





line(190+210,156+c-42,190+210,170+c-42);





line(190+240,156+c-48,190+240,170+c-48);





line(190+270,156+c-55,190+270,170+c-54);





line(190+300,156+c-61,190+300,170+c-61);







line(190+330,78+c+10,190+330,89+c+13);



line(190+360,72+c+11,190+360,85+c+13);

line(190+390,67+c+10,190+390,81+c+10);

line(190+420,62+c+8,190+420,76+c+10);

line(190+449,57+c+8,190+449,71+c+8);









/////////////////road



setcolor(12); /////////////////////////////1



line(1,310,25,306);

line(6,318,30,315);

line(1,310,6,318);

line(25,306,30,314);

int k,m;

k=13*45+19;

m=16*(-8);

//2

setcolor(12);



line(605,310-128,629,306-128);

line(610,318-128,634,315-128);

line(605,310-128,610,318-128);

line(629,306-128,634,314-128);



setcolor(12); //////////////////////////////////3

k=45;

m=-8;

line(46,302,70,298);

line(51,310,75,307);

line(46,302,51,310);

line(70,298,75,306);





setfillstyle(1,0);

floodfill(64,303,12);



setfillstyle(1,14);

floodfill(14,314,12);

floodfill(617,183,12);



setfillstyle(1,0);

floodfill(14,314,12);

floodfill(617,183,12);



setfillstyle(1,14);

floodfill(64,303,12);



t=getch();

if(t=='1')

exit(0);

if(t=='h')

{

sound(710);

delay(500);

nosound();

//break;

}

if(t=='t')

{

while(!kbhit()) {

setfillstyle(1,0);

floodfill(536,213,13);

floodfill(563,213,13);

floodfill(561,244,13);

floodfill(538,244,13);

floodfill(274,295,13);

floodfill(294,295,13);

floodfill(274,265,13);

floodfill(294,265,13);

floodfill(548,250,13);

floodfill(548,214,13);

floodfill(533,228,13);

floodfill(563,228,13);

floodfill(262,281,13);

floodfill(308,281,13);

floodfill(284,251,13);

floodfill(284,295,13);



setfillstyle(1,random(12));



floodfill(200,250,13);

delay(10);

//setfillstyle(1,11);



floodfill(170,250,13);

floodfill(80,230,13);





}



setfillstyle(1,0);



floodfill(200,250,13);

delay(10);

//setfillstyle(1,11);



floodfill(170,250,13);

floodfill(80,230,13);



}





if(t=='l')

{

while(!kbhit())

{



delay(120);

setfillstyle(6,0); //////////////////////////ty

floodfill(536,213,13);

floodfill(563,213,13);

floodfill(561,244,13);

floodfill(538,244,13);

floodfill(274,295,13);

floodfill(294,295,13);

floodfill(274,265,13);

floodfill(294,265,13);



setfillstyle(1,0);

floodfill(64,303,12);



///////////////////////////////////road



setfillstyle(9,0); /////////////////////color

floodfill(81-40+5,419+7,13);

floodfill(151-40,409+7,13);

floodfill(211-40,397+7,13);

floodfill(271-40,380+7,13);

floodfill(331-40,368+7,13);

floodfill(396-40,355+7,13);

floodfill(450-40,345+7,13);

floodfill(510-40,335+7,13);

floodfill(570-40,325+7,13);

floodfill(630-40,312+7,13);





//////////////////////

floodfill(50,197,13);

floodfill(110,177,13);

floodfill(166,165,13);

floodfill(527,86,13);

floodfill(587,71,13);









setfillstyle(6,14); //////////////////////////ty

floodfill(548,250,13);

floodfill(548,214,13);

floodfill(533,228,13);

floodfill(563,228,13);

floodfill(262,281,13);

floodfill(308,281,13);

floodfill(284,251,13);

floodfill(284,295,13);

////////////////////////////////////////road



setfillstyle(9,10);///////////////////////////////////color

floodfill(19,429,13);

floodfill(81,419,13);

floodfill(151,409,13);

floodfill(211,397,13);

floodfill(271,380,13);

floodfill(331,368,13);

floodfill(396,355,13);

floodfill(450,345,13);

floodfill(510,335,13);

floodfill(570,325,13);

floodfill(630,312,13);

//////////////////////////////////////

floodfill(20,197,13);

floodfill(80,187,13);

floodfill(133,174,13);

floodfill(517,86,13);

floodfill(557,81,13);

floodfill(627,70,13);



setfillstyle(1,14);

floodfill(14,314,12);

floodfill(617,183,12);



///////////////////////////////////////

setfillstyle(10,4);

floodfill(302+248,230,13);

floodfill(302+248+v,230+b,13);

///light

setfillstyle(6,11); ///////////



floodfill(200,250,13);



floodfill(170,250,13);

floodfill(80,230,13);



delay(120);



setfillstyle(6,0);/////////////////////ty

floodfill(548,250,13);

floodfill(548,214,13);

floodfill(533,228,13);

floodfill(563,228,13);

floodfill(262,281,13);

floodfill(308,281,13);

floodfill(284,251,13);

floodfill(284,295,13);

/////////////////////////////////////road

setfillstyle(9,0); ///////////////color



floodfill(19,429,13);

floodfill(81,419,13);

floodfill(151,409,13);

floodfill(211,397,13);

floodfill(271,380,13);

floodfill(331,368,13);

floodfill(396,355,13);

floodfill(450,345,13);

floodfill(510,335,13);

floodfill(570,325,13);

floodfill(630,312,13);

///////////////////////////////////////////////////////

floodfill(20,197,13);

floodfill(80,187,13);

floodfill(133,174,13);

floodfill(517,86,13);

floodfill(557,81,13);

floodfill(627,70,13);

/////////////////////////////

setfillstyle(1,0);

floodfill(14,314,12);

floodfill(617,183,12);



setfillstyle(6,10); /////////////ty



floodfill(536,213,13);

floodfill(563,213,13);

floodfill(561,244,13);

floodfill(538,244,13);

floodfill(274,295,13);

floodfill(294,295,13);

floodfill(274,265,13);

floodfill(294,265,13);

////////////////////////////////////////////////road

setfillstyle(9,14);/////////////////////////////////////////color

floodfill(81-40+5,419+7,13);

floodfill(151-40,409+7,13);

floodfill(211-40,397+7,13);

floodfill(271-40,380+7,13);

floodfill(331-40,368+7,13);

floodfill(396-40,355+7,13);

floodfill(450-40,345+7,13);

floodfill(510-40,335+7,13);

floodfill(570-40,325+7,13);

floodfill(630-40,312+7,13);

/////////////////////////////////////////



floodfill(50,197,13);

floodfill(110,177,13);

floodfill(166,165,13);

floodfill(527,86,13);

floodfill(587,71,13);

setfillstyle(1,14);

floodfill(64,303,12);



setfillstyle(9,4);

floodfill(302+248,230,13);

floodfill(302+248+v,230+b,13);



delay(20);

setfillstyle(1,14);



floodfill(200,250,13);



floodfill(170,250,13);

floodfill(80,230,13);



delay(20);

setfillstyle(1,0);



floodfill(200,250,13);



floodfill(170,250,13);

floodfill(80,230,13);









} }









if(t=='p')

{

int n=0;

while(!kbhit())

{

if(n<=60)

n++;

setcolor(0);

rectangle(1+1,-10,90-1,-12+n);

delay(14);



setcolor(9);

rectangle(1,-10,90,-10+n);

if(n==60)

{



outtextxy(10,10,"L-LIGHTS");

outtextxy(10,20,"H-HORN");

//outtextxy(10,30,"T-AllOY");

delay(400);

}





}

setcolor(0);

rectangle(1,-10,90,-10+n);

rectangle(1,-10,90,-11+n);

outtextxy(10,10,"L-LIGHTS");

outtextxy(10,20,"H-HORN");

//outtextxy(10,30,"T-AllOY");



}



}







circle(300,100,3);



nosound();



getch();

}

Computer Graphics - Piano Music

Posted by Sarjukottapuram

#include


#include

#include

#include

/** PC Internal Speaker Required **/

//** Author: Sarju www.sarjus-elearning.blogspot.com **/

main()





{

float octave[7]={130.81,146.83,164.81,174.61,196.220,246.94};
//You can change the music by changing above values
int adn;

while(!kbhit())





{

adn=random(7);

sound(octave[adn]*10);

delay(190);

nosound();

}}

Computer Graphics - BLINCK

Posted by Sarjukottapuram

#include
#include
#include
#include
void main()
{
int gdriver=DETECT,gmode;
int i,x,y;
initgraph(&gdriver,&gmode,"c:\\tc\\bgi");
//"c:\\tc\\bgi" give location in your system where C installed
while(!kbhit())
{
x=random(640);
y=random(480);
setcolor(15);
for(i=1;i<10;i++) { circle(x,y,i); delay(10); } setfillstyle(1,15); line(x+8,y-2,x+40,y); line(x+8,y+2,x+40,y); floodfill(x+11,y,15); line(x-8,y-2,x-40,y); line(x-8,y+2,x-40,y); floodfill(x-11,y,15); line(x-2,y+8,x,y+40); line(x+2,y+8,x,y+40); floodfill(x,y+11,15); line(x-2,y-8,x,y-40); line(x+2,y-8,x,y-40); floodfill(x,y-11,15); line(x+8,y-2,x+20,y-20); line(x+2,y-8,x+20,y-20); floodfill(x+15,y-15,15); line(x+8,y+2,x+20,y+20); line(x+2,y+8,x+20,y+20); floodfill(x+15,y+15,15); line(x-8,y+2,x-20,y+20); line(x-2,y+8,x-20,y+20); floodfill(x-15,y+15,15); line(x-8,y-2,x-20,y-20); line(x-2,y-8,x-20,y-20); floodfill(x-15,y-15,15); sound(4000); setcolor(0); for(i=40;i>=10;i--)
{
line(x+8,y-2,x+i,y);
line(x+8,y+2,x+i,y);
}
for(i=40;i>=10;i--)
{
line(x-8,y-2,x-i,y);
line(x-8,y+2,x-i,y);
}
for(i=40;i>=10;i--)
{
line(x-2,y+8,x,y+i);
line(x+2,y+8,x,y+i);
}
for(i=40;i>=10;i--)
{
line(x-2,y-8,x,y-i);
line(x+2,y-8,x,y-i);
}
for(i=20;i>=7;i--)
{
line(x+8,y-2,x+i,y-i);
line(x+2,y-8,x+i,y-i);
}
for(i=20;i>=7;i--)
{
line(x+8,y+2,x+i,y+i);
line(x+2,y+8,x+i,y+i);
}
for(i=20;i>=7;i--)
{
line(x-8,y+2,x-i,y+i);
line(x-2,y+8,x-i,y+i);
}
for(i=20;i>=7;i--)
{
line(x-8,y-2,x-i,y-i);
line(x-2,y-8,x-i,y-i);
}
for(i=9;i>0;i--)
{
circle(x,y,i);
delay(10);
}
nosound();
}
cleardevice();
setcolor(2);
settextstyle(2,0,5);
outtextxy(220,160,"Creator:SARJU");
outtextxy(265,235,"www.sarjus-elearning.blogspot.com");
getch();getch();
}

Banker's Algorithm - Linux Lab

Posted by Sarjukottapuram

BANKER’S ALGORITHM
Theory
The Banker's algorithm is a resource allocation & deadlock avoidance algorithm developed by Edsger Dijkstra that tests for safety by simulating the allocation of pre-determined maximum possible amounts of all resources, and then makes a "safe-state" check to test for possible deadlock conditions for all other pending activities, before deciding whether allocation should be allowed to continue.
The algorithm was developed in the design process for the THE operating system and originally described (in Dutch) in EWD108[1]. The name is by analogy with the way that bankers account for liquidity constraints.
The Banker's algorithm is run by the operating system whenever a process requests resources.The algorithm prevents deadlock by denying or postponing the request if it determines that accepting the request could put the system in an unsafe state (one where deadlock could occur).
Resources
For the Banker's algorithm to work, it needs to know three things:
• How much of each resource each process could possibly request
• How much of each resource each process is currently holding
• How much of each resource the system has available
Some of the resources that are tracked in real systems are memory, semaphores and interface access.
Example
Assuming that the system distinguishes between four types of resources, (A, B, C and D), the following is an example of how those resources could be distributed. Note that this example shows the system at an instant before a new request for resources arrives. Also, the types and number of resources are abstracted. Real systems, for example, would deal with much larger quantities of each resource.
Available system resources:
A B C D
3 1 1 2
Processes (currently allocated resources):
A B C D
P1 1 2 2 1
P2 1 0 3 3
P3 1 1 1 0
Processes (maximum resources):
A B C D
P1 3 3 2 2
P2 1 2 3 4
P3 1 1 5 0
Safe and Unsafe States
A state (as in the above example) is considered safe if it is possible for all processes to finish executing (terminate). Since the system cannot know when a process will terminate, or how many resources it will have requested by then, the system assumes that all processes will eventually attempt to acquire their stated maximum resources and terminate soon afterward. This is a reasonable assumption in most cases since the system is not particularly concerned with how long each process runs (at least not from a deadlock avoidance perspective). Also, if a process terminates without acquiring its maximum resources, it only makes it easier on the system.
Given that assumption, the algorithm determines if a state is safe by trying to find a hypothetical set of requests by the processes that would allow each to acquire its maximum resources and then terminate (returning its resources to the system). Any state where no such set exists is an unsafe state.
Example
We can show that the state given in the previous example is a safe state by showing that it is possible for each process to acquire its maximum resources and then terminate.
1. P1 acquires 2 A, 1 B and 1 D more resources, achieving its maximum
o The system now still has 1 A, no B, 1 C and 1 D resource available
2. P1 terminates, returning 3 A, 3 B, 2 C and 2 D resources to the system
o The system now has 4 A, 3 B, 3 C and 3 D resources available
3. P2 acquires 2 B and 1 D extra resources, then terminates, returning all its resources
o The system now has 5 A, 3 B, 6 C and 6 D resources
4. P3 acquires 4 C resources and terminates
o The system now has all resources: 6 A, 4 B, 7 C and 6 D
5. Because all processes were able to terminate, this state is safe
Note that these requests and acquisitions are hypothetical. The algorithm generates them to check the safety of the state, but no resources are actually given and no processes actually terminate. Also note that the order in which these requests are generated – if several can be fulfilled – doesn't matter, because all hypothetical requests let a process terminate, thereby increasing the system's free resources.
For an example of an unsafe state, look at what would happen if process 2 were holding 1 more unit of resource B at the beginning.
Requests
When the system receives a request for resources, it runs the Banker's algorithm to determine if it is safe to grant the request. The algorithm is fairly straight forward once the distinction between safe and unsafe states is understood.
1. Can the request be granted?
o If not, the request is impossible and must either be denied or put on a waiting list
2. Assume that the request is granted
3. Is the new state safe?
o If so grant the request
o If not, either deny the request or put it on a waiting list
Whether the system denies an impossible or unsafe request or makes it wait is an operating system specific decision.
Continuing the previous examples, assume process 3 requests 2 units of resource C.
1. There is not enough of resource C available to grant the request
2. The request is denied
On the other hand, assume process 3 requests 1 unit of resource C.
1. There are enough resources to grant the request
2. Assume the request is granted
o The new state of the system would be:
Available system resources: A B C D
Free 3 1 0 2
Processes (currently allocated resources):
A B C D
P1 1 2 2 1
P2 1 0 3 3
P3 1 1 2 0
Processes (maximum resources):
A B C D
P1 3 3 2 2
P2 1 2 3 4
P3 1 1 5 0
1. Determine if this new state is safe
1. P1 can acquire 2 A, 1 B and 1 D resources and terminate
2. Then, P2 can acquire 2 B and 1 D resources and terminate
3. Finally, P3 can acquire 3 C resources and terminate
4. Therefore, this new state is safe
2. Since the new state is safe, grant the request
Finally, assume that process 2 requests 1 unit of resource B.
1. There are enough resources
2. Assuming the request is granted, the new state would be:
Available system resources:
A B C D
Free 3 0 1 2
Processes (currently allocated resources):
A B C D
P1 1 2 2 1
P2 1 1 3 3
P3 1 1 1 0
Processes (maximum resources):
A B C D
P1 3 3 2 2
P2 1 2 3 4
P3 1 1 5 0
1. Is this state safe? Assuming P1, P2, and P3 request more of resource B and C.
o P1 is unable to acquire enough B resources
o P2 is unable to acquire enough B resources
o P3 is unable to acquire enough C resources
o No process can acquire enough resources to terminate, so this state is not safe
2. Since the state is unsafe, deny the request
Algorithm
* The algorithm for the process is...........
1. Start.
2. Wait for the request.
3. If the request is for allocation then
i. Obtain the request.
ii. Check for safe state.
iii. If safe state detected then allocate resources.
Else put the request in the waiting stack.
Else (for deallocation)
i.Deallocate the resources.
ii. Process the request of the process in the
wait stack.
4. Stop.
Program
/* Program to demonstrate the working of the BANKERS ALGORITHM.
* This program gives a general idea of how the operating system process allocates resources to the requesting processes.
* Here it is assumed that request are collected in a 'req_queue' whose type is stored in 'req_type'.
* It has been assumed that there are 3 processes which can request for 4 different types of resources say A,B,C & D.
* The program works with certain assumed values as shown below.........
* This module can be compiled using 'cc bankersalgorithm.c' and executed using './a.out'
//inculsion.
#include
//macro definition
#define cls() printf("\033[H\033[J")
#define delay() for(h=0;h<30000;h++){for(k=0;k<30000;k++){}}
//function prototype.
void getrequest(int);
int issafe();
void allocate(int);
void deallocate(int);
void display();
//global matrixes as shown above.
int available_res[4],cur_allocated_res[3][4],max_req_res[3][4],request[4];
int main()
{
int req_queue[10],wait_queue[10],req_type[10],i,j,h,k;
//inserting the assumed values.
available_res[0]=3; available_res[1]=1; available_res[2]=1; available_res[3]=2;
cur_allocated_res[0][0]=1;cur_allocated_res[0][1]=2;cur_allocated_res[0][2]=2;cur_allocated_res[0][3]=1;
cur_allocated_res[1][0]=1;cur_allocated_res[1][1]=0;cur_allocated_res[1][2]=3;cur_allocated_res[1][3]=3;
cur_allocated_res[2][0]=1;cur_allocated_res[2][1]=1;cur_allocated_res[2][2]=1;cur_allocated_res[2][3]=1;
max_req_res[0][0]=3; max_req_res[0][1]=3; max_req_res[0][2]=2; max_req_res[0][3]=2;
max_req_res[1][0]=1; max_req_res[1][1]=2; max_req_res[1][2]=3; max_req_res[1][3]=4;
max_req_res[2][0]=1; max_req_res[2][1]=1; max_req_res[2][2]=1; max_req_res[2][3]=0;
//assuming the request.
req_queue[0]=0;req_queue[1]=1;req_queue[2]=2;req_queue[3]=0;req_queue[4]=2;req_queue[5]=1;
req_type[0]=0;req_type[1]=0;req_type[2]=0;req_type[3]=1;req_type[4]=1;req_type[5]=1;
display();
i=0;j=0;
while(i<6)
{
cls();
printf("\n\t\t\tWaiting for the request.............\n");
delay();
printf("\n\tRequest obtained from the process P%d ",req_queue[i]+1);
if(req_type[i]==0)
{
printf("for resource allocation.\n");
printf("\nGetting request.....\n");
getrequest(req_queue[i]);
printf("\nChecking safe state.....\n");
delay();
if(issafe())
{
printf("\nSafe state detected....\nAllocating resources .......\n");
allocate(req_queue[i]);
}
else
{
printf("\nUnsafe state detected....\nInserting the process into waiting queue.\n");
j=j+1;
wait_queue[j]=req_queue[i];
}
}
else
{
printf("for resource deallocation.\n");
deallocate(req_queue[i]);
printf("\nDeallocation done.\n\n%d processes in the wait queue\n",j);
if(j>0)
{
while(j>0)
{
printf("\nConsidering the waiting queue process P%d\n",wait_queue[j]+1);
getrequest(wait_queue[j]);
printf("\nChecking safe state.\n");
delay();
if(issafe())
{
printf("\nSafe state detected\nResources allocated\n");
allocate(wait_queue[j]);
j--;
}
else
{
break;
}
}
}
}
delay();
i++;
}
}
void getrequest(int i)
{
int j;
for(j=0;j<4;j++)
{ request[j]=max_req_res[i][j]-cur_allocated_res[i][j];
}
}
int issafe()
{
int j;
for(j=0;j<4;j++)
{
if(request[j]>available_res[j])
{
return 0;
}
}
return 1;
}
void allocate(int i)
{
int j;
for(j=0;j<4;j++)
{
cur_allocated_res[i][j]=cur_allocated_res[i][j]+request[j];
available_res[j]=available_res[j]-request[j];
}
}
void deallocate(int i)
{
int j;
for(j=0;j<4;j++)
{
available_res[j]=available_res[j]+cur_allocated_res[i][j];
cur_allocated_res[i][j]=0;
}
}
void display()
{
int i,j;
char a[3];
cls();
printf("\n\n\n\n\n\n\n\n");
printf("_______________________________________________________________");
printf("\n\n\n\n\t\t\t\tBANKERS ALGORITHM.\n");
printf("\t\t\t\t__________________\n\n\n");
printf("\n\n\n\n\t\tPRESS ENTER TO CONTINUE..................");
fgets(a,2,stdin);
cls();
printf("\n\n\t\t\t\tDETAILS.");
printf("\n\t\t\t\t________");
printf("\n\n\t\tNO OF PROCESSES:\tP1 P2 P3");
printf("\n\n\t\tNO OF RESOURCES:\tA B C D");
printf("\n\n\t\t\tThe status .............");
printf("\nThe available resources are.\n\t\tA B C D\n\t\t");
for(i=0;i<4;i++)
{
printf("%d ",available_res[i]);
}
printf("\nThe currently allocated resources are...\n\t\t A B C D\n\t\t");
for(i=0;i<3;i++)
{
printf("P%d ",i+1);
for(j=0;j<4;j++)
{
printf("%d ",cur_allocated_res[i][j]);
}
printf("\n\t\t");
}
printf("\nThe maximum required resources are...\n\t\t A B C D\n\t\t");
for(i=0;i<3;i++)
{
printf("P%d ",i+1);
for(j=0;j<4;j++)
{
printf("%d ",max_req_res[i][j]);
}
printf("\n\t\t");
}
printf("\n\n\tPRESS ENTER TO START THE PROCESS...\n");
fgets(a,2,stdin);
}

Dining Philosopher's Problem - Linux Lab

Posted by Sarjukottapuram

DINING PHILOSOPHER’S PROBLEM

The problem


The dining philosophers problem is summarized as five philosophers sitting at a table doing one of two things - eating or thinking. While eating, they are not thinking, and while thinking, they are not eating. The five philosophers sit at a circular table with a large bowl of spaghetti in the center. A fork is placed in between each philosopher, and as such, each philosopher has one fork to his or her left and one fork to his or her right. As spaghetti is difficult to serve and eat with a single fork, it must be assumed that in order for a philosopher to eat, the philosopher must have two forks. In the case of the dining philosopher, the philosopher can only use the fork on his or her left or right.
In some cases, the dining philosophers problem is explained using rice and chopsticks as opposed to spaghetti and forks, as it is generally easier to understand that two chopsticks are required, whereas one could arguably eat spaghetti using a single fork, or using a fork and a spoon. In either case, only one instrument (fork or chopstick) can be picked up at a time, and the philosopher must have two instruments in order to eat.


The philosophers never speak to each other, which creates a dangerous possibility of deadlock in which every philosopher holds a left fork and waits perpetually for a right fork (or vice versa).


Originally used as a means of illustrating the problem of deadlock, this system reaches deadlock when there is a 'cycle of ungranted requests'. In this case philosopher P1 waits for the fork grabbed by philosopher P2 who is waiting for the fork of philosopher P3 and so forth, making a circular chain.

Starvation (and the pun was intended in the original problem description) might also occur independently of deadlock if a philosopher is unable to acquire both forks due to a timing issue. For example there might be a rule that the philosophers put down a fork after waiting five minutes for the other fork to become available and wait a further five minutes before making their next attempt. This scheme eliminates the possibility of deadlock (the system can always advance to a different state) but still suffers from the problem of livelock. If all five philosophers appear in the dining room at exactly the same time and each picks up their left fork at the same time the philosophers will wait five minutes until they all put their forks down and then wait a further five minutes before they all pick them up again.

The lack of available forks is an analogy to the locking of shared resources in real computer programming, a situation known as concurrency. Locking a resource is a common technique to ensure the resource is accessed by only one program or chunk of code at a time. When the resource the program is interested in is already locked by another one, the program waits until it is unlocked. When several programs are involved in locking resources, deadlock might happen, depending on the circumstances. For example, one program needs two files to process. When two such programs lock one file each, both programs wait for the other one to unlock the other file, which will never happen.



Algorithm

* The algorithm for the process is..........
1.Start.
2.Initialise the thread variables as required.
3.Create the threads representing philosophers.
4.Wait until the threads finishes execution.
5.Stop.

The algorithm for the philosopher is as..........
1.Start.
2.Wait for the left fork/spoon.
3.Wait for the right fork/spoon.
4.Start eating.
5 Release the left fork/spoon.
6.Release the right fork/spoon.
7.Stop.

Program

/* Program to implement the solution to dinning philosophers' problem.
* This program uses five thread functions as five philosophers.
* The spoons or forks are represented with five semaphore variables.
* To use shared memory just include the code after the sem_wait() in each thread.
* To compile use 'cc diningphilosopher.c -lpthread'.
* To run './a.out'.

//inculsion

#include
#include
#include
//macro definition
#define cls() printf("\033[H\033[J")
#define EATINGTIME 1

//function prototype for the thread function.
void * philosopher1();
void * philosopher2();
void * philosopher3();
void * philosopher4();
void * philosopher5();

//global decalration of semaphore variables.
sem_t sem15,sem12,sem23,sem34,sem45;

//global variable to control the execution of main.
int end=0;
int main()
{
char a[2];
pthread_t t1,t2,t3,t4,t5;
pthread_attr_t at1;
pthread_attr_init(&at1);
pthread_attr_setdetachstate(&at1,PTHREAD_CREATE_DETACHED);
sem_init(&sem15,0,1);
sem_init(&sem12,0,1);
sem_init(&sem23,0,1);
sem_init(&sem34,0,1);
sem_init(&sem45,0,1);
cls();
printf("\n\n\n\n\n\n");
printf("____________________________________________________________________");
printf("\n\n\n\t\t\tDINNING PHILOSOPHER PROBLEM.");
printf("\n\t\t\t____________________________");
printf("\n\n\t\tNO. OF PHILOSOPHERS :5");
printf("\n\n\t\tNO. OF FORKS(SPOONS):5\n\n"); printf("___________________________________");
printf("\n\n\n\t\tPRESS ENTER TO CONTINUE.....................");
fgets(a,2,stdin);
cls();
pthread_create(&t1,&at1,philosopher1,NULL);
pthread_create(&t2,&at1,philosopher2,NULL);
pthread_create(&t3,&at1,philosopher3,NULL);
pthread_create(&t4,&at1,philosopher4,NULL);
pthread_create(&t5,&at1,philosopher5,NULL);
while(end!=5)
{
}
}

//definition of philosopher1.
void * philosopher1()
{
int i=0;
printf("\n\t\tPHILOSOPHER-1 THINKING.\n");
while(i
{
sleep(1);

//waiting to acquire the forks.
sem_wait(&sem15);
sem_wait(&sem12);
printf("\n\t\t\t* PHILOSOPHER-1 EATING.*\n");
sleep(1);

//releasing the forks
sem_post(&sem15);
sem_post(&sem12);
printf("\n\t\tPHILOSOPHER-1 THINKING.\n");
i++;
}
end++;
}

//philosopher2.
void * philosopher2()
{
int i=0;
printf("\n\t\tPHILOSOPHER-2 THINKING.\n");
while(i
{
sleep(1);
sem_wait(&sem12);
sem_wait(&sem23);
printf("\n\t\t\t* PHILOSOPHER-2 EATING.*\n");
sleep(1);
sem_post(&sem12);
sem_post(&sem23);
printf("\n\t\tPHILOSOPHER-2 THINKING.\n");
i++;
}
end++;
}

//philosopher 3
void * philosopher3()
{
int i=0;
printf("\n\t\tPHILOSOPHER-3 THINKING.\n");
while(i
{
sleep(1);
sem_wait(&sem23);
sem_wait(&sem34);
printf("\n\t\t\t* PHILOSOPHER-3 EATING.*\n");
sleep(1);
sem_post(&sem23);
sem_post(&sem34);
printf("\n\t\tPHILOSOPHER-3 THINKING.\n");
i++;
}
end++;
}

//philosopher 4.
void * philosopher4()
{
int i=0;
printf("\n\t\tPHILOSOPHER-4 THINKING.\n");
while(i
{
sleep(1);
sem_wait(&sem34);
sem_wait(&sem45);
printf("\n\t\t\t* PHILOSOPHER-4 EATING.*\n");
sleep(1);
sem_post(&sem34);
sem_post(&sem45);
printf("\n\t\tPHILOSOPHER-4 THINKING.\n");
i++;
}
end++;
}

//philosopher 5.
void * philosopher5()
{
int i=0;
printf("\n\t\tPHILOSOPHER-5 THINKING.\n");
while(i
{
sleep(1);
sem_wait(&sem45);
sem_wait(&sem15);
printf("\n\t\t\t* PHILOSOPHER-5 EATING.*\n");
sleep(1);
sem_post(&sem45);
sem_post(&sem15);
printf("\n\t\tPHILOSOPHER-5 THINKING.\n");
i++;
}
end++;
}

output