Articles by "Os"
Showing posts with label Os. Show all posts
Print Friendly and PDF
no image
Place where all sort of programming stuff and reviews,technology news are shared and Useful Project of C++,C,java C# etc
In computer science, a readers-writer (RW) or shared-exclusive lock (also known as a multiple readers/single-writer lock or multi-reader lock) is a synchronization primitive that solves one of the readers-writers problems. 

An RW lock allows concurrent access for read-only operations, while write operations require exclusive access. This means that multiple threads can read the data in parallel but an exclusive lock is needed for writing or modifying data.  When a writer is writing the data, all other writers or readers will be blocked until the writer is finished writing. A common use might be to control access to a data structure in memory that cannot be updated atomically and is invalid (and should not be read by another thread) until the update is complete.

Readers–writer locks are usually constructed on top of mutexes and condition variables, or on top of semaphores.

The read-copy-update (RCU) algorithm is one solution to the readers-writers problem. RCU is wait-free for readers. The Linux kernel implements a special solution for few writers called seqlock.


Reader Implementation

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/shm.h>
#include "shm_com.h"
#include <string.h>
#include <semaphore.h>
int main(){
int running = 1;int res;
void *shared_memory = (void *)0;struct shared_use_st *shared_stuff;
int shmid;
srand((unsigned int)getpid());shmid = shmget((key_t)1124, sizeof(struct shared_use_st), 0666 | IPC_CREAT);
if (shmid == -1) 
{fprintf(stderr, "shmget Failed\n");
exit(EXIT_FAILURE);
}
shared_memory = shmat(shmid, (void *)0, 0);
if (shared_memory == (void *)-1)
 {
fprintf(stderr, "shmat Failed\n");
exit(EXIT_FAILURE);
}
printf("Memory attached at %x\n", (int)shared_memory);
shared_stuff = (struct shared_use_st *)shared_memory;
shared_stuff->flag = 0;
while(running)
 {
if (shared_stuff->flag)
{
printf("You wrote: %s", shared_stuff->some_text);
sleep( rand() % 4 );sem_wait(shared_stuff->bin_sem);
shared_stuff->flag = 0;
if (strncmp(shared_stuff->some_text, "end", 3) == 0) 
{
running = 0;
}
}
}
if (shmdt(shared_memory) == -1)
 {
fprintf(stderr, "shmdt Failed\n");
exit(EXIT_FAILURE);
}if (shmctl(shmid, IPC_RMID, 0) == -1) 
{
fprintf(stderr, "shmctl(IPC_RMID) Failed\n");exit(EXIT_FAILURE);
}
sem_post(shared_stuff->bin_sem);
exit(EXIT_SUCCESS);
}
Semaphore

#include <semaphore.h>#define TEXT_SZ 2048
struct shared_use_st
 {
sem_t *bin_sem;
char some_text[TEXT_SZ];
int flag;
int res;
};
Writer Implementation

#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include <sys/shm.h>
#include <sys/shm.h>
#include "shm_com.h"
#include <semaphore.h>
int main()
{
int run = 1;
int res;
void *shared_mem = (void *)0;
struct shared_use_st *shared_stuff;
char buffer[BUFSIZ];
int shmid;

shmid = shmget((key_t)1124, sizeof(struct shared_use_st), 0666 | IPC_CREAT);
if (shmid == -1) {
fprintf(stderr, "Semaphore get Failed\n");
exit(EXIT_FAILURE);
}
shared_memory = shmat(shmid, (void *)0, 0);
if (shared_memory == (void *)-1) {
fprintf(stderr, "shmat Failed\n");
exit(EXIT_FAILURE);
}
printf("Memory attached at %x\n", (int)shared_memory);
shared_stuff = (struct shared_use_st *)shared_memory;
while(run) {
while(shared_stuff->flag == 1)
{sleep(1);
sem_post(shared_stuff->bin_sem);
printf("Waiting for client \n");
}
printf("Enter some text: ");
fgets(buffer, BUFSIZ, stdin);
strncpy(shared_stuff->some_text, buffer, TEXT_SZ);
shared_stuff->flag = 1;
if (strncmp(buffer, "end", 3) == 0) 
{
run = 0;
}
}
if (shmdt(shared_memory) == -1) 
{
fprintf(stderr, "shmdt failed\n");
exit(EXIT_FAILURE);
}
sem_wait(shared_stuff->bin_sem);
exit(EXIT_SUCCESS);}
no image
Place where all sort of programming stuff and reviews,technology news are shared and Useful Project of C++,C,java C# etc
PRIORITY SCHEDULING

Program:

#include<stdio.h>
struct process{
int burst,wait,no,priority;
}p[20]={0,0};
int main(){
int n,i,j,totalwait=0,totalturn=0;
printf("\nEnter The No Of Process :");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Enter The Burst Time (in ms) For
Process #%2d :",i+1);
scanf("%d",&p[i].burst);
printf("Enter The Priority For Process
#%2d :",i+1);
scanf("%d",&p[i].priority);
p[i].no=i+1;
}
for(i=0;i<n;i++)
for(j=0;j<n-i-1;j++)
if(p[j].priority>p[j+1].priority){
p[j].burst^=p[j+1].burst^=p[j].burst^=p[j+1]
.burst;
p[j].no^=p[j+1].no^=p[j].no^=p[j+1].no;
//Simple way to swap 2 var’s
p[j].priority^=p[j+1].priority^=p[j].priority^
=p[j+1].priority;
//printf("j");
}
printf("\nProcess \t Starting Ending
Waiting TurnAround ");
printf("\n \t Time Time Time
Time ");
for(i=0;i<n;i++){
printf("\nProcess # %-11d%-10d%-10d%-
10d%10d",p[i].no,p[i].wait,p[i].wait+p[i].bu
rst,p[i].wait,p[i].wait+p[i].burst);
p[i+1].wait=p[i].wait+p[i].burst;
totalwait=totalwait+p[i].wait;
totalturn=totalturn+p[i].wait+p[i].burst;
}
printf("\n\nAverage\n---------");
printf("\nWaiting Time : %f
ms",totalwait/(float)n);
printf("\nTurnAround Time : %f
ms\n\n",totalturn/(float)n);
return 0;
}
Output:
Enter The No Of Process :3
Enter The Burst Time (in ms) For Process #1 :30
Enter The Priority For Process # 1 :2
Enter The Burst Time (in ms) For Process #2 :20
Enter The Priority For Process # 2 :1
Enter The Burst Time (in ms) For Process #3 :40
Enter The Priority For Process # 3 :3
Process Starting Ending Waiting

TurnAround

Time Time Time Time
Process # 2 0 20 0 20
Process # 1 20 50 20 50
Process # 3 50 90 50 90
Average
---------
Waiting Time : 23.333333 ms
TurnAround Time : 53.333333 ms

ROUND ROBIN SCHEDULING

Program:

#include<stdio.h>
struct process
{
int burst,wait,comp,f;
}
p[20]={0,0};
int main()
{
int
n,i,j,totalwait=0,totalturn=0,quantum,flag=1,
time=0;
printf("\nEnter The No Of Process :");
scanf("%d",&n);
printf("\nEnter The Quantum time (in ms):");
scanf("%d",&quantum);
for(i=0;i<n;i++)
{
printf("Enter The Burst Time (in ms) For
Process #%2d :",i+1);
scanf("%d",&p[i].burst);
p[i].f=1;
}
printf("\nOrder Of Execution \n");
printf("\nProcess Starting Ending
Remaining");
printf("\n Time Time Time");
while(flag==1)
{
flag=0;
for(i=0;i<n;i++)
{
if(p[i].f==1)
{
flag=1;
j=quantum;
if((p[i].burst-p[i].comp)>quantum)
{
p[i].comp+=quantum;
}
else
{
p[i].wait=time-p[i].comp;
j=p[i].burst-p[i].comp;
p[i].comp=p[i].burst;
p[i].f=0;
}
printf("\nprocess # %-3d %-10d %-10d
%-10d",i+1,time,time+j,p[i].burstp[i].comp);
time+=j;
}
}
}
printf("\n\n------------------");
printf("\nProcess \t Waiting Time
TurnAround Time ");
for(i=0;i<n;i++)
{
printf("\nProcess # %-12d%-15d%-
15d",i+1,p[i].wait,p[i].wait+p[i].burst);
totalwait=totalwait+p[i].wait;
totalturn=totalturn+p[i].wait+p[i].burst;
}
printf("\n\nAverage\n------------------");
printf("\nWaiting Time : %f
ms",totalwait/(float)n);
printf("\nTurnAround Time : %f
ms\n\n",totalturn/(float)n);
return 0;
}

Output:

Enter The No Of Process :3
Enter The Quantum time (in ms) :5
Enter The Burst Time (in ms) For Process #
1 :25
Enter The Burst Time (in ms) For Process #
2 :30
Enter The Burst Time (in ms) For Process #
3 :54

Order Of Execution

Process Starting Ending Remaining

Time Time Time
process # 1 0 5 20
process # 2 5 10 25
process # 3 10 15 49
process # 1 15 20 15
process # 2 20 25 20
process # 3 25 30 44
process # 1 30 35 10
process # 2 35 40 15
process # 3 40 45 39
process # 1 45 50 5
process # 2 50 55 10
process # 3 55 60 34
process # 1 60 65 0
process # 2 65 70 5
process # 3 70 75 29
process # 2 75 80 0
process # 3 80 85 24
process # 3 85 90 19
process # 3 90 95 14
process # 3 95 100 9
process # 3 100 105 4
process # 3 105 109 0

Process Waiting Time Turn Around Time


Process # 1 40 65
Process # 2 50 80
Process # 3 55 109
Average
Waiting Time : 48.333333 ms
TurnAround Time : 84.666667 ms
no image
Place where all sort of programming stuff and reviews,technology news are shared and Useful Project of C++,C,java C# etc
FIRST COME FIRST SERVED (FCFS)

Program:


#include<stdio.h>
struct process
{
int burst,wait;
}
p[20]={0,0};
int main()
{
int n,i,totalwait=0,totalturn=0;
printf("\nEnter The No Of Process :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter The Burst Time (in ms) For Process #%2d :",i+1);
scanf("%d",&p[i].burst);
}
printf("\nProcess \t Waiting Time TurnAround Time ");
printf("\n \t (in ms) (in ms)");
for(i=0;i<n;i++)
{
printf("\nProcess # %-12d%-15d%-15d",i+1,p[i].wait,p[i].wait+p[i].burst);
p[i+1].wait=p[i].wait+p[i].burst;
totalwait=totalwait+p[i].wait;
totalturn=totalturn+p[i].wait+p[i].burst;
}
printf("\n\nAVERAGE\n--------- ");
printf("\nWaiting Time : %f ms",totalwait/(float)n);
printf("\nTurnAround Time : %f ms\n\n",totalturn/(float)n);
return 0;
}
Output:

Enter The No Of Process :3
Enter The Burst Time (in ms) For Process # 1 :10
Enter The Burst Time (in ms) For Process # 2 :30
Enter The Burst Time (in ms) For Process # 3 :20
Process Waiting Time TurnAround Time
(in ms) (in ms)
Process # 1 0 10
Process # 2 10 40
Process # 3 40 60


AVERAGE
---------
Waiting Time : 16.666667 ms
TurnAround Time : 36.666667 ms


SHORTEST JOB FIRST(SJF)

Program:


#include<stdio.h>
struct process{
int burst,wait,no;
}p[20]={0,0};
int main()
{
int n,i,j,totalwait=0,totalturn=0;
printf("\nEnter The No Of Process :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter The Burst Time (in ms) For Process #%2d :",i+1);
scanf("%d",&p[i].burst);
p[i].no=i+1;
}
for(i=0;i<n;i++)
for(j=0;j<n-i-1;j++)
if(p[j].burst>p[j+1].burst){
p[j].burst^=p[j+1].burst^=p[j].burst^=p[j+1].burst;
p[j].no^=p[j+1].no^=p[j].no^=p[j+1].no;
}
printf("\nProcess \t Waiting Time TurnAround Time ");
for(i=0;i<n;i++){
printf("\nProcess # %-12d%-15d%-15d",p[i].no,p[i].wait,p[i].wait+p[i].burst);
p[i+1].wait=p[i].wait+p[i].burst;
totalwait=totalwait+p[i].wait;
totalturn=totalturn+p[i].wait+p[i].burst;
}
printf("\n\nAverage\n---------");
printf("\nWaiting Time : %f ms",totalwait/(float)n);
printf("\nTurnAround Time : %f ms\n\n",totalturn/(float)n);
return 0;
}

Output:


Enter The No Of Process :3
Enter The Burst Time (in ms) For Process # 1 :20
Enter The Burst Time (in ms) For Process # 2 :30
Enter The Burst Time (in ms) For Process # 3 :10
Process Waiting Time TurnAround Time
Process # 3 0 10
Process # 1 10 30
Process # 2 30 60
Average
---------
Waiting Time : 13.333333 ms
TurnAround Time : 33.333333 ms


no image
Place where all sort of programming stuff and reviews,technology news are shared and Useful Project of C++,C,java C# etc

#include<iostream>
#include<pthread.h>
#include<iostream>
void* fibonacci(void*);
using namespace std;
int n;
void* fibonnacci(void* arg)
{
int c, first = 0, second = 1, next;
for ( c = 0 ; c <n; c++ )
{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
cout << next << endl;
}
}
int main()
{
pthread_t t;
cout << "Enter the number of terms of Fibonacci series you want" << endl;
cin >> n;
cout << "First " << n << " terms of Fibonacci series are :- " << endl;
pthread_create (&t , NULL , fibonacci,(void*)&n);
return 0;
}
no image
Place where all sort of programming stuff and reviews,technology news are shared and Useful Project of C++,C,java C# etc

#include<iostream>
#include<pthread.h>
using namespace std;
int num;
void* factorial()
{
int fac=1;
for(int a=1;a<=num;a++) 
{
fac=fac*a;
cout<<"Factorial of Given Number is ="<<fac;
}
}
int main()
{
pthread_t t;
cout<<" Enter Number To Find Its Factorial: ";
cin>>num;
pthread_create (&t,NULL,factorial,(void*)&num);return 0;
}
no image
Place where all sort of programming stuff and reviews,technology news are shared and Useful Project of C++,C,java C# etc
int sem_init(sem_t *sem, int pshared, unsigned int value);
The sem_init() function is used to initialize the semaphore's value. The pshared argument must be 0 for semaphores local to a
process. int sem_wait(sem_t * sem);


The sem_wait() function performs the equivalent of the down semaphore operation.
int sem_post(sem_t * sem);
The sem_post() function performs the equivalent of the up semaphore operation.
int sem_destroy(sem_t * sem);
The sem_destroy() function is used to properly deallocate resources alloted to a semaphore. The semaphore in this program is used
as a mutex, a binary semaphore, to implement mutual exclusion between two processes which use a shared resource.


Program

#include <unistd.h> /* Symbolic Constants */
#include <sys/types.h> /* Primitive System Data Types */
#include <errno.h> /* Errors */
#include <stdio.h> /* Input/Output */
#include <stdlib.h> /* General Utilities */
#include <pthread.h> /* POSIX Threads */
#include <string.h> /* String handling */
#include <semaphore.h> /* Semaphore */
/* prototype for thread routine */
void handler ( void *ptr );
/* global vars */
/* semaphores are declared global so they can be accessed
in main() and in thread routine,
here, the semaphore is used as a mutex */
sem_t mutex;
int counter; /* shared variable */
int main()
{
int i[2];
pthread_t thread_a;
pthread_t thread_b;
i[0] = 0; /* argument to threads */
i[1] = 1;
sem_init(&mutex, 0, 1); /* initialize mutex to 1 - binary semaphore */
/* second param = 0 - semaphore is local */
/* Note: you can check if thread has been successfully created by checking return value
of
pthread_create */
pthread_create (&thread_a, NULL, (void *) &handler, (void *) &i[0]);
pthread_create (&thread_b, NULL, (void *) &handler, (void *) &i[1]);
pthread_join(thread_a, NULL);
pthread_join(thread_b, NULL);
sem_destroy(&mutex); /* destroy semaphore */
/* exit */
exit(0);
} /* main() */
void handler ( void *ptr )
{
int x;
x = *((int *) ptr);
printf("Thread %d: Waiting to enter critical region...\n", x);
sem_wait(&mutex); /* down semaphore */
/* START CRITICAL REGION */
printf("Thread %d: Now in critical region...\n", x);
printf("Thread %d: Counter Value: %d\n", x, counter);
printf("Thread %d: Incrementing Counter...\n", x);
counter++;
printf("Thread %d: New Counter Value: %d\n", x, counter);
printf("Thread %d: Exiting critical region...\n", x);
/* END CRITICAL REGION */
sem_post(&mutex); /* up semaphore */
pthread_exit(0); /* exit thread */
}
no image
Place where all sort of programming stuff and reviews,technology news are shared and Useful Project of C++,C,java C# etc

Thread synchronization problem

#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_t tid[2];
int counter;
void* doSomeThing(void *arg)
{
unsigned long i = 0;
counter += 1;
printf("\n Job %d started\n", counter);
for(i=0; i<(0xFFFFFFFF);i++);
printf("\n Job %d finished\n", counter);
return NULL;
}
int main(void)
{
int i = 0;
int err;
while(i < 2)
{
err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
if (err != 0)
printf("\ncan't create thread :[%s]", strerror(err));
i++;
}
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
return 0;
}

Above example using mutex (Problem solved)


#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_t tid[2];
int counter;
pthread_mutex_t lock;
void* doSomeThing(void *arg)
{
pthread_mutex_lock(&lock);
unsigned long i = 0;
counter += 1;
printf("\n Job %d started\n", counter);
for(i=0; i<(0xFFFFFFFF);i++);
printf("\n Job %d finished\n", counter);
pthread_mutex_unlock(&lock);
return NULL;
}
int main(void)
{
int i = 0;
int err;
if (pthread_mutex_init(&lock, NULL) != 0)
{
printf("\n mutex init failed\n");
return 1;
}
While (i < 2)
{
err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
if (err != 0)
printf("\ncan't create thread :[%s]", strerror(err));
i++;
}
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
pthread_mutex_destroy(&lock);
return 0;
}
no image
Place where all sort of programming stuff and reviews,technology news are shared and Useful Project of C++,C,java C# etc

The producer-consumer problem:

Consider the standard producer-consumer problem. Assume, we have a buffer of 4096 byte length. A
producer thread will collect the data and writes it to the buffer. A consumer thread will process the collected
data from the buffer. Objective is, both the threads should not run at the same time.
solve it via Semaphore and  mutex  via consumer-producer problem.

Some Basic Concepts:

Using Mutex:

A mutex provides mutual exclusion, either producer or consumer can have the key (mutex) and proceed withtheir work. As long as the buffer is filled by producer, the consumer needs to wait, and vice versa.At any point of time, only one thread can work with the entire buffer. The concept can be generalized usingsemaphore.


Using Semaphore:


A semaphore is a generalized mutex. Instead of single buffer, we can split the 4 KB buffer into four 1 KBbuffers (identical resources). A semaphore can be associated with these four buffers. The consumer andproducer can work on different buffers at the same time.Binary semaphore:


Misconception:


There is an ambiguity between binary semaphore and mutex. We might have come across that a mutex is
binary semaphore. But they are not! The purpose of mutex and semaphore are different. May be, due to
similarity in their implementation a mutex would be referred as binary semaphore.
Strictly speaking, a mutex is locking mechanism used to synchronize access to a resource. Only one task (can
be a thread or process based on OS abstraction) can acquire the mutex. It means there will be ownership
associated with mutex, and only the owner can release the lock (mutex).
Semaphore is signaling mechanism (“I am done, you can carry on” kind of signal). For example, if you are
listening songs (assume it as one task) on your mobile and at the same time your friend called you,
an interrupt will be triggered upon which an interrupt service routine (ISR) will signal the call processing task
to wakeup.

Implementation By a Semaphore 

#include <iostream>
#include <unistd.h> 
#include <sys/types.h> 
#include <errno.h>
#include <stdlib.h> 
#include <pthread.h> 
#include <string.h> 
#include <semaphore.h>

using namespace std;  
int b,x;
pthread_t tid1,tid2; 
sem_t mutex;  
void* job1(void *arg)
{    sem_wait(&mutex);   
           
    cout<<"Enter polynomial values 4X^2 + 5X";
cin>>x;

b=x*x*4;
    sem_post(&mutex); 
    return NULL;
 }  
void* job2(void *arg) 
{
sem_wait(&mutex); 
b=b + 5*x;
x=b;

sem_post(&mutex);
}

int main(void) {  
   int i = 0;
 sem_init(&mutex, 0, 1);  
    pthread_create(&tid1, NULL, &job1, NULL);
    pthread_create(&tid2, NULL, &job2, NULL);
    pthread_join(tid1, NULL);   
    pthread_join(tid2, NULL);
    cout<<"Result"<<x<<"\n";    
    sem_destroy(&mutex);   
    return 0; } 

Implementation By a Mutex

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
using namespace std;  
int x,b;  
pthread_t tid1,tid2; 
pthread_mutex_t lock;  
void* job1(void *arg) 
{   
pthread_mutex_lock(&lock);        
    cout<<"Enter polynomial values 4X^2 + 5x";
cin>>x;
b=x*x*4;
     pthread_mutex_unlock(&lock);
    return NULL;
 }  
void* job2(void *arg) 
{
pthread_mutex_lock(&lock); 
b= b+ 5*x;
x=b;
 pthread_mutex_unlock(&lock);
}
 int main(void)
{  
 int i = 0;    
 int err;  
  if (pthread_mutex_init(&lock, NULL) != 0)   
  {        
cout<<"mutex init failed";
 return 1;    
 }  
pthread_create(&tid1, NULL, &job1, NULL);
pthread_create(&tid2, NULL, &job2, NULL);

pthread_join(tid1, NULL);    
pthread_join(tid2, NULL);  

cout<<"Result="<<x<<"\n";    
pthread_mutex_destroy(&lock);  
    return 0; 
} 


no image
Place where all sort of programming stuff and reviews,technology news are shared and Useful Project of C++,C,java C# etc
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <string.h>
#include<unistd.h>
int main()
{int menu = 0;
printf("\n\n\n");
printf("************************ Code By ******************** \n");
printf(" avb\n");
printf("********************* WELCOME *********************** \n"); 
do
{
printf("\n\n");
printf("1. Create and write a File \n");
printf("2. Read from a File\n");
printf("3. Pipe\n");
printf("4. dup2\n");
printf("5. Fork\n");
printf("6. To exit from the program\n");
printf("Hello User please Enter your choice =");

scanf("%d", &menu); 
switch 
(menu) 
{
case 1:
{
FILE *fptr;
char name[20];
int age;
float salary;
fptr = fopen ("emp.rec", "w"); /*open for writing*/
if (fptr == NULL)
{
printf("File does not exists\n");
return;
}
printf("Enter the name\n");
scanf("%s", name);
fprintf(fptr, "Name = %s\n", name);
printf("Enter the age\n");
scanf("%d", &age);
fprintf(fptr, "Age = %d\n", age);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary = %.2f\n", salary);
fclose(fptr);
break;
}
case 2:
{
FILE * pFile;
char ch, file_name [250];
pFile = fopen ("emp.rec" , "r");
if (pFile == NULL) perror ("Error opening file");else {

printf("The contents of %s file are :\n", file_name);
while( ( ch = fgetc(pFile) ) != EOF )
printf("%c",ch);fclose(pFile);
}

break;
} 
case 3:
{
void write_to_pipe (int file)
{
FILE *stream;
stream = fdopen (file, "w");
fprintf (stream, "hello, world!\n");
fprintf (stream, "goodbye, world!\n");
fclose (stream);
}
void read_from_pipe (int file)
{
FILE *stream;
int c;
stream = fdopen (file, "r");
while ((c = fgetc (stream)) != EOF)
putchar (c);
fclose (stream);
}
pid_t pid;
int mypipe[2];
/* Create the pipe. */
if (pipe (mypipe))
{
fprintf (stderr, "Pipe failed.\n");
// return EXIT_FAILURE;
}
/* Create the child process. */
pid = fork ();
if (pid == (pid_t) 0)
{
/* This is the child process.
Close other end first. */
close (mypipe[1]);
read_from_pipe (mypipe[0]);
// return EXIT_SUCCESS;
}
else if (pid < (pid_t) 0)
{
/* The fork failed. */
fprintf (stderr, "Fork failed.\n");
return EXIT_FAILURE;
}
else
{
/* This is the parent process.
Close other end first. */
close (mypipe[0]);
write_to_pipe (mypipe[1]);
//return EXIT_SUCCESS;}

break;
}case 4
{

//First, we're going to open a file
int file = open("myfile.txt", O_APPEND | O_WRONLY);
if(file < 0) return 1;//Now we redirect standard output to the file using dup2
if(dup2(file,1) < 0) return 1;

//Now standard out has been redirected, we can write to
// the file
printf( "This will print in myfile.txt\n" ); return 0;

break;
}//end of function main
case 5:
{

{
int i = 1;
pid_t child_pid;
printf("The main program process ID is %d", (int) getpid());
printf("%d", i);
child_pid = fork();
if (child_pid != 0) {
i++;
printf("%d", i);
printf("This is the parent process, with ID %d \n", (int) getpid());
printf("The child process is %d ", (int) child_pid);
}
 else 
{
printf("%d", i);
printf("This is the child process, with ID %d \n", (int) getpid());
}
}
return 1;
break; 
}
default;
{printf("You are out of prog\n");

} 
}
}while(menu!=6);
return 0;
}
no image
Place where all sort of programming stuff and reviews,technology news are shared and Useful Project of C++,C,java C# etc

#include<stdio.h>
int mutex=1,full=0,empty=3,x=0;
main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf("\n 1.Producer \n 2.Consumer \n 3.Exit");
while(1){
printf("\n Enter your choice:");
scanf("%d",&n);
switch(n)
{
case 1:
if((mutex==1)&&(empty!=0))
producer();
else
printf("Buffer is full");
break;
case 2:
if((mutex==1)&&(full!=0))
consumer();else
printf("Buffer is empty");
break;
case 3:
exit(0);
break;
}
}
}
int wait(int s)
{
return (--s);
}
int signal(int s)
{
return(++s);
}
void producer()
{
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x++;
printf("\n Producer produces the item %d",x);
mutex=signal(mutex);
}
void consumer()
{
mutex=wait(mutex);
full=wait(full);empty=signal(empty);
printf("\n Consumer consumes item %d",x);
x--;
mutex=signal(mutex);
}
no image
Place where all sort of programming stuff and reviews,technology news are shared and Useful Project of C++,C,java C# etc
#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
#define N 5
#define THINKING 0
#define HUNGRY 1#define EATING 2
#define LEFT (ph_num+4)%N
#define RIGHT (ph_num+1)%N
sem_t mutex;
sem_t S[N];void * philospher(void *num);
void take_fork(int);
void put_fork(int);
void test(int);
int state[N];
int phil_num[N]={0,1,2,3,4};
int main()
{
int i;
pthread_t thread_id[N];
sem_init(&mutex,0,1);
for(i=0;i<N;i++)
sem_init(&S[i],0,0);
for(i=0;i<N;i++)
{
pthread_create(&thread_id[i],NULL,philospher,&phil_num[i]);
printf("Philosopher %d is thinking\n",i+1);
}
for(i=0;i<N;i++)
pthread_join(thread_id[i],NULL);
}
void *philospher(void *num)
{
int fk = 0;
while(fk < 1)
{
int *i = num;
sleep(1);
take_fork(*i);
sleep(0);
put_fork(*i);
fk++;
}
}
void take_fork(int ph_num){
sem_wait(&mutex);
state[ph_num] = HUNGRY;
printf("Philosopher %d is Hungry\n",ph_num+1);
test(ph_num);sem_post(&mutex);
sem_wait(&S[ph_num]);
sleep(1);
}void test(int ph_num)
{
if (state[ph_num] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING)
{
state[ph_num] = EATING;
sleep(2);
printf("Philosopher %d takes fork %d and %d\n",ph_num+1,LEFT+1,ph_num+1);
printf("Philosopher %d is Eating\n",ph_num+1);
sem_post(&S[ph_num]);
}}
void put_fork(int ph_num)
{
sem_wait(&mutex);
state[ph_num] = THINKING;
printf("Philosopher %d putting fork %d and %d down\n",ph_num+1,LEFT+1,ph_num+1);
printf("Philosopher %d is thinking\n",ph_num+1);
test(LEFT);
test(RIGHT);sem_post(&mutex);
}
no image
Place where all sort of programming stuff and reviews,technology news are shared and Useful Project of C++,C,java C# etc
#include <stdio.h>                /* standard I/O routines */
#include <pthread.h>        /* pthread functions and data structures */
#include <unistd.h>

                                            /* function to be executed by the new thread */
void*
do_loop(void* data)
{
int i;                                                       /* counter, to print numbers */
int j;                                                      /* counter, for delay */
int me = *((int*)data);                     /* thread identifying number */
printf("I am %d, mypid is %d\n", me, getpid());
for (i=0; i<10; i++) 
{
for (j=0; j<500000; j++)            /* delay loop */;
printf("'%d' - Got '%d'\n", me, i);
}
                                                      /* exit the thread */
pthread_exit(NULL);}
/* like any C program, program's execution begins in main */
intmain(int argc, char* argv[])
{int thr_id;                     /* thread ID for the newly created thread */
pthread_t p_thread; /* thread's structure */
int a = 1;                     /* thread 1 identifying number */
int b = 2;                  /* thread 2 identifying number */
int c = 3;                 /* thread 2 identifying number */
                               /* create a new thread that will execute 'do_loop()' */
thr_id = pthread_create(&p_thread, NULL, do_loop, (void*)&a);thr_id = pthread_create(&p_thread, NULL, do_loop, (void*)&b);

                       /* run 'do_loop()' in the main thread as well */do_loop((void*)&c);
                     /* NOT REACHED */return 0;
}
no image
Place where all sort of programming stuff and reviews,technology news are shared and Useful Project of C++,C,java C# etc
#include <iostream>
#include <stdio.h>
int curr[5][5], maxclaim[5][5], avl[5];
int alloc[5] = {0,0,0,0,0};
int maxres[5], running[5], safe=0;
int count = 0, i, j, exec, r, p,k=1;
int main()
{
printf("\nEnter the number of processes: ");
scanf("%d",&p);
for(i=0;i<p;i++)
{
running[i]=1;
count++;
}
printf("\nEnter the number of resources: ");
scanf("%d",&r);
for(i=0;i<r;i++)
{ 
printf("\nEnter the resource for instance %d: ",k++);
scanf("%d",&maxres[i]);
}
printf("\nEnter Claim matrix:\n");
for(i=0;i<p;i++)
{
for(j=0;j<r;j++)
{
scanf("%d",&maxclaim[i][j]);
}
}
printf("\nEnter Allocation matrix:\n");
for(i=0;i<p;i++)
{
for(j=0;j<r;j++)
{
scanf("%d",&curr[i][j]);
}
}
printf("\n The total resourse instances are: ");
for(i=0;i<r;i++)
{
printf("\t%d",maxres[i]);
}
printf("\nThe allocation matrix:\n");
for(i=0;i<p;i++)
{
for(j=0;j<r;j++)
{
printf("\t%d",curr[i][j]);
}
printf("\n");
}
printf("\nThe claim matrix:\n");
for(i=0;i<p;i++)
{
for(j=0;j<r;j++)
{
printf("\t%d",maxclaim[i][j]);
}
printf("\n");
}
for(i=0;i<p;i++)
{
for(j=0;j<r;j++)
{
alloc[j]+=curr[i][j];
}
}
printf("\nAllocated resources:");
for(i=0;i<r;i++)
{
printf("\t%d",alloc[i]);
}
for(i=0;i<r;i++)
{
avl[i]=maxres[i]-alloc[i];
}
printf("\nAvailable resources:");

for(i=0;i<r;i++)
{
printf("\t%d",avl[i]);
}
printf("\n");
                          //Main procedure goes below to check for unsafe state.
while(count!=0)
{
safe=0;
for(i=0;i<p;i++)
{
if(running[i])
{
exec=1;
for(j=0;j<r;j++)
{
if(maxclaim[i][j] - curr[i][j] > avl[j])
{
exec=0;
break;
}
}
if(exec)
{
printf("\nProcess%d is executing\n",i+1), "\n";
running[i]=0;
count--;
safe=1;
for(j=0;j<r;j++) 
{
avl[j]+=curr[i][j];
}
break;
}
}
}
if(!safe)
{
printf("\nThe processes are in unsafe state.\n");
break;
}
else
{
printf("\nThe process is in safe state");
printf("\nThe awailable resources after the execution of process :" , i+1 ,"is");
for(i=0;i<r;i++)
{
printf("\t%d",avl[i]);
}
printf("\n");
}
}
system ("pause");
}
no image
Place where all sort of programming stuff and reviews,technology news are shared and Useful Project of C++,C,java C# etc
#include<conio.h>
#include<windows.h>
#include<iostream>
using namespace std;
int main()
{
   int c;
   system("Color FC");
   cout<<"\n\t\t     Choose your desired option"<<endl;
   cout<<"\t\t\t1 ->First Fit"<<endl;
   cout<<"\t\t\t2 ->Best Fit "<<endl;
   cout<<"\t\t\t3 ->Worst Fit"<<endl;
   cout<<"\t\t\t4 ->Next Fit "<<endl;
   cout<<"\t\t\tenter choice:\t";
   cin>>c;
   if(c==4)
  { 
    int p,m;  
    cout<<"Enter number of processes : ";
    cin>>p;
    cout<<"Enter number of Memory blocks : ";
    cin>>m;
    int parr[p],marr[m],i;
    for(i=0;i<p;i++)
    {
    cout<<"Enter size of process "<<(i+1)<<" : ";
    cin>>parr[i];      
    }
    for(i=0;i<m;i++)
    {
    cout<<"Enter size of memory "<<(i+1)<<" ";
    cin>>marr[i];      
     }
     int j=0;
     for(i=0;i<p;i++)
     {
     cout<<" search  "<< i<<" "<< j;
      for(;;j=(j+1)%m)
      {
      if(marr[j]>=parr[i])
      {
       marr[j]-=parr[i];
       cout<<"Allocating process to memory";
       cout<<"\n Size remaining in it after allocation ";
       cout<<(i+1)<<" "<<(j+1)<<" "<<marr[j];   
       cout<<j<<(j+1)%m;
        break;            
        }  
        }    
        if(j==m)
        {
        cout<<"Not enough memory for process "<<i;
        break;
        }        
        }
         getch();
       }        
       else if(c==1 || c==2 || c==3)
       {
       int i,j,k,n,l,m[10],p[10],po[20],flag,z,y,temp,temp1;
       cout<<"enter memory partition:\t";
       cin>>n;
       cout<<"\nenter memory size for\n";
       for(i=1;i<=n;i++)
       {
       cout<<"\npartition "<<i<<" :\t";
       cin>>m[i];
       po[i]=i;       
       }
          cout<<"\nenter process:\t";
          cin>>j;
          cout<<"\nenter memory size for\n";
          for(i=1;i<=j;i++)
          {
              cout<<"\nprocess "<<i<<" :\t";
              cin>>p[i];                 
          }        
          switch(c)
          {
             case 1:
             for(i=1;i<=j;i++)
    {
    flag=1;
    for(k=1;k<=n;k++)
    {
   if(p[i]<=m[k])
   {
   cout<<"\nprocess "<<i<<" whose memory size is "<<p[i];
   cout<<"KB allocated at memory partition : "<<po[k]<<endl;;
   if(p[i]<m[k])
   {
   cout<<"internal fragmentation is : "<<(m[k]-p[i]);
   }
   else
   {
   cout<<"external fragmentation is : "<<(p[i]-m[k]);
    }
    m[k]=m[k]-p[i];
    break;           
    }
    else
    {
     flag++;  
     }
     }     
    if(flag>n)
     {
     cout<<"\nprocess "<<i<<" whose memory size is "<<p[i];
     cout<<"KB can't be allocated";       
     }           
     }
     break;
     case 2:
     for(y=1;y<=n;y++)
     {
     for(z=y;z<=n;z++)
     {
     if(m[y]>m[z])
     {
      temp=m[y];
      m[y]=m[z];
      m[z]=temp;
      temp1=po[y]; 
       po[y]=po[z];
       po[z]=temp1;            
       }                  
       }              
       }
       for(i=1;i<=j;i++)
       {
       flag=1;
       for(k=1;k<=n;k++)
       {
      if(p[i]<=m[k])
      {
      cout<<"\nprocess "<<i<<" whose memory size is "<<p[i];
     cout<<"KB allocated at memory partition : "<<po[k]<<endl;
     if(p[i]<m[k])
        {
      cout<<"internal fragmentation is : "<<(m[k]-p[i]);
        }
       else
         {
   cout<<"external fragmentation is : "<<(p[i]-m[k]);
    }
    m[k]=m[k]-p[i];
   break;           
   }
   else
  {
  flag++;  
  }
  }   
  if(flag>n)
  {
  cout<<"\nprocess "<<i<<" whose memory size is "<<p[i];
  cout<<"KB can't be allocated";       
  }           
  }
  break;
  case 3:
  for(y=1;y<=n;y++)
  {
  for(z=y;z<=n;z++)
  {
  if(m[y]<m[z])
  {
  temp=m[y];
  m[y]=m[z];
  m[z]=temp;
  temp1=po[y]; 
  po[y]=po[z];
  po[z]=temp1;            
  }                 
  }              
  }
  for(i=1;i<=j;i++)
 {
 flag=1;
  for(k=1;k<=n;k++)
  {
  if(p[i]<=m[k])
 {
 cout<<"\nprocess "<<i<<" whose memory size is "<<p[i];
 cout<<"KB allocated at memory partition : "<<po[k]<<endl;
 if(p[i]<m[k])
 {
 cout<<"internal fragmentation is : "<<(m[k]-p[i]);
 }
 else
 {
 cout<<"external fragmentation is : "<<(p[i]-m[k]);
 }
 m[k]=m[k]-p[i];
 break;           
 else
{
flag++;  
}
}   
if(flag>n)
{
cout<<"\nprocess "<<i<<" whose memory size is "<<p[i];
cout<<"KB can't be allocated";       
}          
}
break;
}  
getch();
}
}