Showing posts with label UNIX PROGRAMS. Show all posts
Showing posts with label UNIX PROGRAMS. Show all posts

Tuesday, November 22

5 PROCESSES TO CHECK ARMSTRONG AND REVERSE OF NUMBER~ Unix Program

Hi reader,
  Here our task is :

  • Create 5 processes.
  • Find whether a number is Armstong and Reverse the same using these processes.



A :Accept number.
C:Find whether it is armstrong.
D:Print Result.
B:Calculate Reverse of the Number.
E:Display Reverse.



Here is the complete Program.


#include<stdio.h>
#include<unistd.h>
main()
{             //initially in A

int num,f1,f2,f3,f4,p1[2],p2[2],p3[2],p4[2],arm,rev,flag=0;
pipe(p1);
pipe(p2);


f1=fork();  //A created B
if(f1>0)    //A is working ..
{
f2=fork();  //A created C

if(f2>0)     //A is working...
{
printf("Enter a number   :");
scanf("%d",&num);


close(p1[0]);
close(p2[0]);
write(p1[1],&num,sizeof(num));
write(p2[1],&num,sizeof(num));
}
if(f2==0)   //C is working..
{


pipe(p3);
f3=fork(); //C created D

if(f3>0)   //C is working..
{
close(p1[1]);
read(p1[0],&num,sizeof(num));
flag=0;

for(arm=0;num>0;num/=10)
arm+=(num%10)*(num%10)*(num%10);

if(num==arm)flag=1;
close(p3[0]);
write(p3[1],&flag,sizeof(flag));
}
else if (f3==0)  //D is working..
{

close(p3[1]);
read(p3[0], &flag, sizeof(flag));
(flag)?printf("It is Armstrong Number"):("It is Not Armstrong Number");

}
}
}
if(f1==0)   //B is working..

{
sleep(2);
pipe(p4);
f4=fork(); //B created E

if(f4>0)   //B is working..{
close(p2[1]);
read(p2[0],&num,sizeof(num));
for(rev=0;num>0;num/=10)
rev=10*rev+num%10;
close(p4[0]);
write(p4[1],&rev,sizeof(rev));
}
if(f4==0)   //E is working..

{
close(p4[1]);
read(p4[0],&rev,sizeof(rev));
printf("Reverse of Number is : %d\n",rev);
}
}
}





Output
Enter a number: 153
It is Armstrong Number
Reverse of Number is :351

Monday, October 10

SEMAPHORES TO IMPLEMENT PRODUCER CONSUMER PROBLEM

#include<sys/sem.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/types.h>
#include<stdio.h>
#include<sys/ipc.h>
void up(int);
void down(int);
union value
{
int val;
struct semid_ds *buf;
unsigned short *array;
struct seminto *_buf;
}
main()
{
int mutex,full,empty,pid,i,key,j,k;
union value arg;
key=ftok("",'a');
mutex=semget(key,1,0660|IPC_CREAT);
arg.val=0;
semctl(full,0,SETVAL,arg);
key=ftok("",'c');
empty=semget(key,1,0660|IPC_CREAT);
arg.val=4;
semctl(empty,0,SETVAL,arg);
pid=fork();
switch(pid)
{
case -1:
printf("Error");
case 0:
sleep(13);
printf("\n");
printf("Consumer consuming items\n");
for(i=0;i<5;i++)
{
down(full);
down(mutex);
for(j=4-i;j>=1;j--)
printf("*");
for(k=0;k<=i;k++)
printf("_");
printf("\n");
fflush(stdout);
up(mutex);
up(empty);
sleep(1);
}
printf("Buffer empty\n");
break;
default:
printf("Producer producing items\n");
for(i=0;i<5;i++)
{
down(full);
down(mutex);
//printf("producer is producing %dth item\n",i);
for(j=4-i;j>=1;j--)
printf("_");
for(k=0;k<=i;k++)
printf("*");
printf("\n");
fflush(stdout);
up(mutex);
up(full);
sleep(1);
}
printf("Buffer full\n");
break;
}}
void down(int id)
{
struct sembuf sb={0,-1,0};
semop(id,&sb,1);
}
void up(int id)
{
struct sembuf sb={0,1,0};
semop(id,&sb,1);
}

Saturday, October 8

udp communication

Hi Viewer,

Here is a simple java program showing client-server interacion using UDP.
In tgis example, client will send a message and the sever will reply back with same message after converting it to Uppercase..!!



server.java


import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[])throws Exception
{
DatagramSocket serverSocket=new DatagramSocket(1249);
byte[] receiveData=new byte[1024];
byte[] sendData=new byte[1024];
while(true)
{
DatagramPacket receivePacket=new DatagramPacket(receiveData,receiveData.length);
serverSocket.receive(receivePacket);
String sentence=new String(receivePacket.getData());
InetAddress IPAddress=receivePacket.getAddress();
int port=receivePacket.getPort();
String capitalizedSentence=sentence.toUpperCase();
sendData=capitalizedSentence.getBytes();
DatagramPacket sendPacket=new DatagramPacket(sendData,sendData.length,IPAddress,port);
serverSocket.send(sendPacket);
}
}
}










client.java


import java.io.*;
import java.net.*;
class UDPClient
{
public static void main(String args[])throws Exception
{
BufferedReader inFromUser=new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket=new DatagramSocket();
InetAddress IPAddress=InetAddress.getByName("localhost");
byte[] sendData=new byte[1024];
byte[] receiveData=new byte[1024];
System.out.println("Enter msg:");
String sentence=inFromUser.readLine();
sendData=sentence.getBytes();
DatagramPacket sendPacket=new DatagramPacket(sendData,sendData.length,IPAddress,1249);
clientSocket.send(sendPacket);
DatagramPacket receivePacket=new DatagramPacket(receiveData,receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence=new String(receivePacket.getData());
System.out.println("FROM SERVER:"+modifiedSentence);
clientSocket.close();
}
}




If you have any suggestion, or doubt on it, please do comment here.!! Thank you.!! :)

Wednesday, September 21

Check a Number in parent process and pass result to Child Process

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



main()
{
int fd[2],f,i,num,flag=1;
pipe(fd);
f=fork();

if(f>0)
{
printf("PARENT PROCESS..");
printf("\nEnter a number : ");
scanf("%d",&num);



if(num==1)flag=0;for(i=2;i<=(num/2);i++)
if(num%i==0)
{
flag=0;
break;
}

close(fd[0]);
write(fd[1],&flag,sizeof(flag));



}
else if (f==0)
{

printf("\n\nCHILD PROCESS.");close(fd[1]);
read(fd[0],&flag,sizeof(flag
));

if(flag==1)printf(" \n\tIt is a prime number..\n");
else printf("\n\t It is not a prime number..\n");
}



}

Saturday, August 13

Create a Pipe and print descriptive value








program


#include<stdio.h>
main()
{
int f[2];
pipe(f);
printf("Pipe Descriptive values are  %d and %d ", f[0],f[1]);
}


Create a Child process and print process-id


(i) Using one fork() system call

#include<stdio.h>
main()
{
      int f,c,p;
      f=fork();
      if(f==0)
      {
              c=getpid();
              printf("Child Process\n pid: %d",c);
              c=getppid();
              printf("\tppid :%d \n",c);
      }
      else if(f>0)
      {
           sleep(1);
           c=getpid();
           printf("\nParent Process\n pid: %d",c);
           c=getppid();
           printf("\tppid :%d\n\n",c);
      }
}
     
     
     
     

Sunday, July 31

C PROGRAM TO DISPLAY TYPE OF A FILE






Hi Friends,

This is my C program to check the type of a file in UNIX system. Before going to program, have a look on what actually a 'type' means in UNIX system. A file may be one of the  following types :
  1. Regular File  : It may be either a text file or a binary file.
  2. Directory File : These are the files that can store other files (like file folder we use) so that users can organise their files into some hierarchical manner.!!)
  3. Character Device File : It refers to a physical device that transmits data in a character-based manner. (like printer, modems, consoles),
  4. Block Device File : Similar to character device file, but it can transmit a block  of data at a time.
  5. FIFO FILE : A special pipe device file which furnishes a temporary buffer for 2 or more processes to communicate (by writing to / reading data from buffer).
Note: A single device can have both block and character device files representing them for different access methods.Consider F be a character device file on its creation. But F can be used by a hard disk to bulk/ non-blocking data transfer between a process and the disk.


         Here is the complete program. . .

TYPECHECK.C 


 /*
PROGRAM NAME: TYPECHECK.C
AIM : TO READ A FILE NAME AND DISPLAY IT'S TYPE
DATE : 07/31/2011
*/

  #include<stdio.h>                                                                           
  #include<sys/stat.h>                                          
                                                                             
  main ()
 {   
    char file_name[20];
    struct stat p;
    printf("\nEnter filename :  ");
    scanf("%s",file_name);
    stat(file_name,&p);
    printf("\a\n%s is a ",file_name); 
    if(S_ISREG(p.st_mode))
    printf("regular file");
     else if(S_ISDIR(p.st_mode))
     printf("directory file");
     else if(S_ISCHR(p.st_mode))
     printf("character file");
     else if(S_ISBLK(p.st_mode))
     printf("block file");
      else if(S_ISFIFO(p.st_mode))
      printf("FIFO file");
      
else
      printf("Unknown type file or not found..!!");
      getch();
     
 }                   





Saturday, July 30

To Read Student Details and Make Rank List

Here is a simple C program that can be used to input students details. The program can store the details into a file and from that file it can make a rank list which can be written to another file.!! On reading the aim it is obvious that actual file handling may not be in same manner. But this program surely introduce you how Actual file 'read ' and 'write' occurs. Here we go..




STUDENT.C

/*
*PROGRAM NAME:STUDENT.C
*AIM : TO READ STUDENT DETAILS AND MAKE PROGRESS REPORT IN A FILE
*OUTPUT FILE: STUDENT.TXT , PROGRESS. TXT
*DATE: 07/30/2011
*/




#include<stdio.h>
#include<fcntl.h>
struct student
{
       int roll_no,total;
       char Name[10];
        }
       buff,stud[20];
      
       int main()
       {

           int count,i,j;
           int fd=open("STUDENT.TXT",O_WRONLY|O_APPEND);  //open 'student.txt' to write unsorted student-details
           printf("Enter the no. of students..");
           scanf("%d",&count);
           for( i=0;i<count;printf("\n"))
           {
           printf("Student %d\n",++i);
           printf("Roll no : ");
           scanf("%d",&buff.roll_no);
           printf("Name : ");
           scanf("%s",buff.Name);
           printf("Total Marks : ");
           scanf("%d",&buff.total);
           write(fd,&buff,sizeof(buff));  //Store each data in a "buffer" structure and append to 'student.txt'..
           }                                            
            close(fd);
            
             fd=open("STUDENT.TXT",O_RDONLY);
            int fd2=open("PROGRESS.TXT",O_WRONLY);
            count=0;
            while(read(fd,&buff,sizeof(buff))>0)  //Open 'student.txt' in read mode and copy data to structure-array..
                 stud[count++]=buff;
                
               for(i=0;i<count;i++)                //Sort the details in structure array
               for(j=0;j< count-i-1;j++)
               if(stud[j].total<stud[j+1].total)
               {
                buff=stud[j];
                stud[j]=stud[j+1];
                stud[j+1]=buff;
                }
               for(i=0;i<count;i++)
               write(fd2,&stud[i],sizeof(stud[i]));//Write back the sorted details to 'progress.txt'..
               close(fd2);
               close(fd);
               fd2=open("PROGRESS.TXT",O_RDONLY); //Open 'progress.txt' file to read and display ranklist 
               printf("\n\tPROGRESS REPORT\n\t_______________\n\n\n RANK\t NAME \tROLLNO\tMARKS\n\n");
               i=0;
               while(read(fd2,&buff,sizeof(buff))>0)
               printf("\n (%d)\t%s\t%d\t%d",++i,buff.Name,buff.roll_no,buff.total);
               getch();
                           }

Display the Contents of a Directory





    Here is a simple program to open and display the contents of a directory.
                                             

 DIRECTORY.C

/*
PROGRAM NAME:DIRECTORY.C
AIM:TO DISPLAY THE CONTENTS OF A DIRCTORY
DATE:07/30/2011
*/
#include<stdio.h>
#include<dirent.h>

main()
{
char dirname[10];
DIR *ptr;
struct dirent *dir;
printf("Enter the directory Name..");
scanf("%s",dirname);
ptr=opendir(dirname);

printf("\nContents in %s are..\n",dirname);
while((dir=readdir(ptr))!=NULL)
printf("%s\n",dir->d_name);
getch();
closedir(ptr);
}



Note

  • System calls for directory operations are included in the header file <dirent.h>.
  • opendir: Opens afile directory.
  • closedir: Closes a directory.
  • readdir : Reads the next record from file.
  • rewinddir: Sets file pointer to the beginning of file.