os
#!/bin/sh The sign #! is called she-bang and is written at the top of the script. It passes instructions to program /bin/sh
clear
i="y"
echo "Enter name of database " # displays a line of text
read db # take the input from keyboard
while [ $i = "y" ]
do
clear
echo "1.View the Data Base oF Books"
echo "2.View Specific Books "
echo "3.Add Books "
echo "4.Delete Books "
echo "5.Exit "
echo "Enter your choice "
read ch
case $ch in
1)cat $db;; # cat-used to display the contents of a small file on terminal
2)echo "Enter id "
read id
grep -i "$id" $db;; #grep -print those lines which matches the pattern -i is case-insensative search
3)echo "Enter new id "
read tid
echo "Enter new Book Name:"
read tnm
echo "Enter new Auther Name"
read des
echo "$tid $tnm $des ">>$db;;
4)echo "Enter Id"
read id
sed '/$id/d' $db>dbs1 #stream editor performs searching,insertion,deletion,replace and find
grep -v "$id" $db >dbs1 # -v is invert match, eg find all lines that do not match
echo "Record is deleted"
cat dbs1;;
5)exit;;
*)echo "Invalid choice ";;
esac
echo "Do u want to continue ?"
read i
if [ $i != "y" ]
then
exit
fi
done
*****************************************************************************
2A
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
void mergesort(int a[],int i,int j);
void merge(int a[],int i1,int j1,int i2,int j2);
void quicksort(int number[25],int first,int last){
int i, j, pivot, temp;
if(first<last){
pivot=first;
i=first;
j=last;
while(i<j){
while(number[i]<=number[pivot]&&i<last)
i++;
while(number[j]>number[pivot])
j--;
if(i<j){
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
quicksort(number,first,j-1);
quicksort(number,j+1,last);
}
}
int main()
{
int a[30],n,i;
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
pid_t pid;
pid=fork();
if(pid==0) //child process
{
sleep(10); //when child sleeps parent completes it execution and make orphan process
printf("\ncalling MERGE SORT by child process...\n");
printf("Child process id is: %d\n",(int)getpid());
printf("Parent process id is: %d\n",(int)getppid());
mergesort(a,0,n-1);
printf("\nSorted array is :");
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}
else if(pid>0) //parent process
{
//sleep(10); //when parent sleeps child completes it execution and make zombi process
printf("\ncalling QUICK SORT by parent process....\n");
printf("Child process id is: %d\n",(int)getpid());
printf("Parent process id is: %d\n",(int)getppid());
quicksort(a,0,n-1);
printf("Order of Sorted elements: ");
for(i=0;i<n;i++)
printf(" %d",a[i]);
printf("\n");
}
else if(pid<0){
printf("\n\nfork failed.....\n");
}
return 0;
}
void mergesort(int a[],int i,int j)
{
int mid;
if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid); //left recursion
mergesort(a,mid+1,j); //right recursion
merge(a,i,mid,mid+1,j); //merging of two sorted sub-arrays
}
}
void merge(int a[],int i1,int j1,int i2,int j2)
{
int temp[50]; //array used for merging
int i,j,k;
i=i1; //beginning of the first list
j=i2; //beginning of the second list
k=0;
while(i<=j1 && j<=j2) //while elements in both lists
{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while(i<=j1) //copy remaining elements of the first list
temp[k++]=a[i++];
while(j<=j2) //copy remaining elements of the second list
temp[k++]=a[j++];
//Transfer elements from temp[] back to a[]
for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j];
}
***********************************
2B
1)#include <stdio.h>
#include<string.h>
#include<stdlib.h>
void binary_search();
int a[50], n, item, loc, beg, mid, end, i;
void main(int argc,char *argv[])
{
n= atoi(argv[1]);
printf("n=%d",n);
for(i=0;i<n;i++)
{
a[i]= atoi(argv[i+2]);
}
printf("\nEnter ITEM to be searched: ");
scanf("%d", &item);
binary_search();
exit(EXIT_SUCCESS);
}
void binary_search()
{
beg = 0;
end = n-1;
mid = (beg + end) / 2;
while ((beg<=end) && (a[mid]!=item))
{
if (item < a[mid])
end = mid - 1;
else
beg = mid + 1;
mid = (beg + end) / 2;
}
if (a[mid] == item)
printf("\n\nITEM found at location %d\n", mid+1);
else
printf("\n\nITEM doesn't exist\n");
}
*******************************
2)
#include<stdio.h>
#include<sys/types.h>
#include<string.h>
#include<stdlib.h>
void bubble_sort(int[], int);
int main(int argc,char *argv[]) {
char *en[]={NULL};
char * carray[10], *ch;
pid_t pid;int n=5;
int arr[30], num, i;
printf("\nEnter no of elements :");
scanf("%d", &num);
printf("\nEnter array elements :");
for (i = 0; i < num; i++)
scanf("%d", &arr[i]);
bubble_sort(arr, num);
char c1[sizeof(int)];
snprintf(c1,sizeof(int),"%d",n);
ch=malloc(sizeof(c1));
strcpy(ch,c1);
for(i=0;i<n;i++)
{
char c[sizeof(int)];
snprintf(c,sizeof(int),"%d",arr[i]);
carray[i]=malloc(sizeof(c));
strcpy(carray[i],c);
}
char *newargv[]={NULL,NULL,NULL,NULL};
newargv[0]=argv[1];
newargv[1]=ch;
int j=2;
for(i=0;i<n;i++)
{
newargv[j]=carray[i];
j++;
}
pid=fork();
if(pid==0)
{
execve(argv[1],newargv,en);
exit(EXIT_FAILURE);
}
else if(pid>0)
{
printf("\nparent is executing\n");
wait();
}
else if(pid<0)
{
printf("\n Fork cannot be created");
}
return(0);
}
void bubble_sort(int iarr[], int num) {
int i, j, k, temp;
printf("\nUnsorted Data:");
for (k = 0; k < num; k++) {
printf("%5d", iarr[k]);
}
for (i = 1; i < num; i++) {
for (j = 0; j < num - 1; j++) {
if (iarr[j] > iarr[j + 1]) {
temp = iarr[j];
iarr[j] = iarr[j + 1];
iarr[j + 1] = temp;
}
}
printf("\nAfter pass %d : ", i);
for (k = 0; k < num; k++) {
printf("%5d", iarr[k]);
}
}
}
*******************
3.thread
# include <stdio.h>
# include <pthread.h>
int A[10][10];
int B[10][10];
int C[10][10];
#define SIZE 10
int r1,c1,r2,c2;
void *multiply(void* para);
typedef struct values {
int tid;//Thread Id //
int val1,val2;
int mult;
} values;
void accept_matrix(int M[SIZE][SIZE], int rows, int cols)
{
int i, j;
printf("\nEnter values in matrix:\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
scanf("%d",&M[i][j]);
}
}
}
void display_matrix(int M[SIZE][SIZE], int rows, int cols)
{
int i, j;
printf("\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
printf("%2d ",M[i][j]);
}
printf("\n");
}
}
int main()
{
pthread_t tid[1000]; //Max No. of Thread //
int i,j,k,l;
int *mult=0;
values v;
printf("Enter Number of Rows For Matrix 1 :");
scanf("%d",&r1);
printf("Enter Number of Columns For Matrix 1 :");
scanf("%d",&c1);
accept_matrix(A, r1,c1);
printf("\n");
printf("Enter Numer of Rows For Matrix 2 :");
scanf("%d",&r2);
printf("Enter Number of Columns For Matrix 2 :");
scanf("%d",&c2);
accept_matrix(B, r2,c2);
if(c1!=r2)
{
printf("Multipication of Matrix not Possible !!!");
}
else
{
for(i=0;i<r1;i=i+2)
{
for(j=0;j<c2;j=j+2)
{
C[i][j]=0;
}
}
v.val1=v.val2=v.mult=0;
l=0;
for(i=0;i<r1;i=i+1)
{
for(j=0;j<c2;j++)
{
for(k=0;k<c1;k++)
{
v.val1=v.val2=v.mult=0;
v.tid=l++;
v.val1 = A[i][k];
v.val2 = B[k][j];
pthread_create(&tid[l],NULL,multiply,&v);
// int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *),void *arg)
// creates thread and run the program concerrently returns 0 on sucess and garbage on failure
pthread_join(tid[l],(void**)&mult); //waits for the thread specified by 'thread' to terminate
// syntax: int pthread_join(pthread_t thread, void ** ret_val)
printf(" %d",mult);
sleep(2);
C[i][j]=C[i][j]+(int)mult;
}
}
}
}
printf("\nMatrix A:");
display_matrix(A, r1, c1);
printf("\nMatrix B:");
display_matrix(B, r2, c2);
printf("\n Multipication of Matrix ...\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("%d \t",C[i][j]);
}
printf("\n");
}
return 0;
}
void *multiply(void* para)
{
values *v = (values*)para;
v->mult = v->val1*v->val2;
printf("\nFinishing thread %d\t",v->tid);
printf("thread finished ... %u\n",(unsigned int)pthread_self()); //returns id of thread which is invoked
pthread_exit((void*)v->mult); //terminates the calling thread and returns a value which is
//available to another thread in the same process that calls pthread_join()
//syntax: void pthread_exit(void *ret_val)
}
*************************************************************
4.mutex
#include <stdio.h>
#include <pthread.h>
#define MAX 10 /* Numbers to produce */
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;//condp=1
int buffer = 0;
void producer(void *ptr) {
int i;
for (i = 1; i <= MAX; i++) {
while (buffer != 0) /* If there is something in the buffer then wait */
{ pthread_cond_wait(&condp, &the_mutex); }//condp=0
buffer = i;
printf("Producer is producing.....%d\n",buffer);
pthread_cond_signal(&condc); /* wake up consumer */
pthread_mutex_unlock(&the_mutex); /* release the buffer */
}
pthread_exit(0);
}
void consumer(void *ptr) {
int i;
for (i = 1; i <= MAX; i++) {
pthread_mutex_lock(&the_mutex); /* protect buffer */
while (buffer == 0) /* If there is nothing in the buffer then wait */
{ pthread_cond_wait(&condc, &the_mutex); }
printf("Consumer is consuming.....%d\n",buffer);
buffer = 0;
pthread_cond_signal(&condp); /* wake up producer */
pthread_mutex_unlock(&the_mutex); /* release the buffer */
}
pthread_exit(0);
}
int main(int argc, char **argv) {
pthread_t pro, con;
// Initialize the mutex and condition variables
pthread_mutex_init(&the_mutex, NULL);
pthread_cond_init(&condc, NULL); /* Initialize consumer condition variable */
pthread_cond_init(&condp, NULL); /* Initialize producer condition variable */
// Create the threads
pthread_create(&con, NULL, (void*)consumer, NULL);
pthread_create(&pro, NULL, (void*)producer, NULL);
pthread_join(con, NULL);
pthread_join(pro, NULL);
pthread_mutex_destroy(&the_mutex); /* Free up the_mutex */
pthread_cond_destroy(&condc); /* Free up consumer condition variable */
pthread_cond_destroy(&condp); /* Free up producer condition variable */
pthread_kill(con);
pthread_kill(pro);
}
***********************
sema
#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
#include<stdlib.h>
#define size 5
int buffer[size],counter;
sem_t available;
sem_t occupied;
sem_t mutex;
void initialize()
{
//sem_init(sem_t semaphore,);
sem_init(&available,0,size);
sem_init(&occupied,0,0);
sem_init(&mutex,0,1);
counter=1;
}
void *producer()
{
int val=0,i=0;
while(1){
sem_getvalue(&available,&val);
if(val==0)
printf("Buffer overflow....producer have to wait.....\n\n");
sem_wait(&available);//4
sem_wait(&mutex);//0
buffer[i%size]=counter;
printf("producer has produced %d...\n",counter);
sleep(2);
counter++;i++;
sem_post(&mutex);//1
sem_post(&occupied);//1
}
pthread_exit((void *)0);
}
void *consumer()
{
int val=0,i=0;
while(1){
sem_getvalue(&occupied,&val);
if(val==0)
printf("Buffer underflow...consumer have to wait...\n\n");
sem_wait(&occupied);//0
sem_wait(&mutex);//0
printf("consumer has consumed %d...\n",buffer[i%size]);
buffer[i%size]=0;
sleep(2);
i++;
sem_post(&mutex);//1
sem_post(&available);//5
}
pthread_exit((void *)0);
}
int main()
{
pthread_t producer_thread1,consumer_thread;
//pthread_t producer_thread2;
initialize();
pthread_create(&consumer_thread,NULL,consumer,NULL);
pthread_create(&producer_thread1,NULL,producer,NULL);
//pthread_create(&producer_thread2,NULL,producer,NULL);
pthread_join(producer_thread1,NULL);
//pthread_join(producer_thread2,NULL);
pthread_join(consumer_thread,NULL);
pthread_kill(producer_thread1);
//pthread_kill(producer_thread2);
pthread_kill(consumer_thread);
return 0;
}
********************************************
5.reader writer
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
pthread_mutex_t x,wsem;
pthread_t tid;
int readcount,writecount;
void initialize()
{
pthread_mutex_init(&x,NULL);
pthread_mutex_init(&wsem,NULL);
readcount=0;writecount=0;
}
void *reader(void *param)
{
int waittime;
waittime=rand()%5;
printf("\n reader is waiting to enter");
pthread_mutex_lock(&x);
readcount++;
if(readcount==1)
pthread_mutex_lock(&wsem);
printf("\n %d reader is inside",readcount);
pthread_mutex_unlock(&x);
sleep(waittime);
pthread_mutex_lock(&x);
readcount--;
if(readcount==0)
pthread_mutex_unlock(&wsem);
pthread_mutex_unlock(&x);
printf("\n reader is leaving");
}
void *writer(void *param)
{
int waittime;
waittime=rand()%3;
printf("\n writer is waiting to enter");
pthread_mutex_lock(&wsem);
writecount++;
printf("\n %d writer has entered",writecount);
sleep(waittime);
pthread_mutex_unlock(&wsem);
printf("\n %d writer is leaving",writecount);
sleep(30);
exit(0);
}
int main()
{
int n1,n2,i;
initialize();
printf("\n enter no. of readers:");
scanf("%d",&n1);
printf("\n enter the no. of writer:");
scanf("%d",&n2);
for(i=0;i<n1;i++)
pthread_create(&tid,NULL,reader,NULL);
for(i=0;i<n2;i++)
pthread_create(&tid,NULL,writer,NULL);
sleep(3);
printf("\n");
exit(0);
return 0;
}
*************************************************
6.dining
#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
#define N 5
#define thinking 1
#define hungry 2
#define eating 3
#define LEFT (ph_num + 4) % N
#define RIGHT (ph_num + 1) % N
int state[N];
int phil_num[N]={0,1,2,3,4};
sem_t lock;
sem_t S[N];
void test(int ph_num)
{
if(state[ph_num]==hungry &&
state[LEFT]!=eating && state[RIGHT]!=eating)
{
state[ph_num]=eating;
sleep(5);
printf("Philosopher %d takes fork %d and %d\n",ph_num+1, LEFT+1, ph_num+1);
printf("Philosopher %d is Eating\n\n", ph_num+1);
}
}
void take_fork(int ph_num)
{
sem_wait(&lock);
state[ph_num]=hungry;
printf("philosopher %d is hungry\n",ph_num);
test(ph_num);
sem_post(&lock);
sleep(2);
}
void put_fork(int ph_num)
{
sem_wait(&lock);
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\n", ph_num + 1);
test(LEFT);
test(RIGHT);
sem_post(&lock);
}
void *philosopher(void *num)
{
while(1)
{
int *i=num;
sleep(1);
take_fork(*i);
sleep(1);
put_fork(*i);
}
}
int main()
{
int i;
pthread_t thread_id[N];
sem_init(&lock, 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,philosopher, &phil_num[i]);
printf("Philosopher %d is thinking\n", i + 1);
}
for (i = 0; i < N; i++)
pthread_join(thread_id[i], NULL);
return 0;
}
********************************************
7.fifo
1)
#include<stdio.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<unistd.h>
#include<string.h>
#define MAX_BUF 80
int main(){
int fd,i = 0;
char *myfifo="/tmp/myfifo";
char str[MAX_BUF]="";
char ch;
mkfifo(myfifo,0666);
printf("\nEnter a string : ");
fgets(str,MAX_BUF,stdin);
fd=open(myfifo,O_WRONLY);
write(fd,str,strlen(str));
close(fd);
unlink(myfifo);
return 0;
}
2)
#include<stdio.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<unistd.h>
#include<string.h>
#define MAX_BUF 1024
int main()
{
int fd,k,i, c=0,c1=0;
char *myfifo="/tmp/myfifo";
char str[MAX_BUF]="";
mkfifo(myfifo,0666);
fd=open(myfifo,O_RDONLY);
read(fd,str,sizeof(str));
printf("\nReceived Messaged= %s\n",str);
k=strlen(str)-1;
printf("length = %d\n",k);
for(i=0;str[i]!='\0';i++)
if(str[i]==' ')
c++;
for(i=0;str[i]!='\0';i++)
if(str[i]=='\n')
c1++;
printf("\n\nTotal lines are %d\n",c1);
printf("\n\nTotal words are %d\n ",c+1);
close(fd);
return 0;
}
***************************************************
PIPE
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
int main()
{
int fd1[2],fd2[2],nbytes;
pid_t childpid;
char str[]="/root/Desktop/Welcome";
FILE *fp;
char readbuffer[100],buffer[200]="",filebuf[20];
pipe(fd1);
pipe(fd2);
printf("pipe created...\n");
if((childpid=fork())==1)
{
perror("fork");
exit( 1);
}
//childpid = fork();
if(childpid==0) //child process
{
//reads the content of file on first pipe
close(fd1[1]);
nbytes=read(fd1[0],readbuffer,sizeof(readbuffer));
printf("\nfile path: %s\n",readbuffer);
fp=fopen(readbuffer,"r");
while(!feof(fp))
{
if(fgets(filebuf,strlen(filebuf)+1,fp)!=NULL)
{strcat(buffer,filebuf);}
}
//writes the contents of the file on second pipe
close(fd2[0]);
printf("\nChild writes the contents of file on second pipe:\n");
printf("%s\n",buffer);
write(fd2[1],buffer,strlen(buffer)+1);
exit(0);
}
else { //parent process
//writes a pathname of file on first pipe
close(fd1[0]);
write(fd1[1],str,strlen(str)+1);
// close(fd1[1]);
//reads the contents of file on second pipe
sleep(2);
close(fd2[1]);
nbytes=read(fd2[0],readbuffer,sizeof(readbuffer));
printf("\nParent reads the contents of file on second pipe:\n");
puts(readbuffer);
}
return 0;
}
-***************************************
8.
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include<stdio.h>
#include<string.h>
int main()
{
int retval,shmid;
void *memory=NULL;
char *p;
// Initialization of shared memory
shmid=shmget((key_t)123456789,6,IPC_CREAT|0666);
if(shmid<0)
{
printf("Failure in creation ");
shmid=shmget((key_t)123456789,6,0666);
}
printf("\n We are getting the shared memory created %d \n",shmid);
// Attachment to shared memory
memory=shmat(shmid,NULL,0);
if(memory==NULL)
{
printf("\n Attachment failure");
return 0;
}
p=(char *)memory;
memset(p,'\0',6);
memcpy(p,"hello",6);
retval=shmdt(p);
if(retval<0)
{
printf("Suffered detachment");
return 0;
}
}
/**OUTPUT
[student@localhost Downloads]$ gcc shmwrite.c
[student@localhost Downloads]$ ./a.out
We are getting the shared memory created 1835015
[student@localhost Downloads]$
*/
****************************************************
9.
clear
i="y"
echo "Enter name of database " # displays a line of text
read db # take the input from keyboard
while [ $i = "y" ]
do
clear
echo "1.View the Data Base oF Books"
echo "2.View Specific Books "
echo "3.Add Books "
echo "4.Delete Books "
echo "5.Exit "
echo "Enter your choice "
read ch
case $ch in
1)cat $db;; # cat-used to display the contents of a small file on terminal
2)echo "Enter id "
read id
grep -i "$id" $db;; #grep -print those lines which matches the pattern -i is case-insensative search
3)echo "Enter new id "
read tid
echo "Enter new Book Name:"
read tnm
echo "Enter new Auther Name"
read des
echo "$tid $tnm $des ">>$db;;
4)echo "Enter Id"
read id
sed '/$id/d' $db>dbs1 #stream editor performs searching,insertion,deletion,replace and find
grep -v "$id" $db >dbs1 # -v is invert match, eg find all lines that do not match
echo "Record is deleted"
cat dbs1;;
5)exit;;
*)echo "Invalid choice ";;
esac
echo "Do u want to continue ?"
read i
if [ $i != "y" ]
then
exit
fi
done
*****************************************************************************
2A
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
void mergesort(int a[],int i,int j);
void merge(int a[],int i1,int j1,int i2,int j2);
void quicksort(int number[25],int first,int last){
int i, j, pivot, temp;
if(first<last){
pivot=first;
i=first;
j=last;
while(i<j){
while(number[i]<=number[pivot]&&i<last)
i++;
while(number[j]>number[pivot])
j--;
if(i<j){
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
quicksort(number,first,j-1);
quicksort(number,j+1,last);
}
}
int main()
{
int a[30],n,i;
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
pid_t pid;
pid=fork();
if(pid==0) //child process
{
sleep(10); //when child sleeps parent completes it execution and make orphan process
printf("\ncalling MERGE SORT by child process...\n");
printf("Child process id is: %d\n",(int)getpid());
printf("Parent process id is: %d\n",(int)getppid());
mergesort(a,0,n-1);
printf("\nSorted array is :");
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}
else if(pid>0) //parent process
{
//sleep(10); //when parent sleeps child completes it execution and make zombi process
printf("\ncalling QUICK SORT by parent process....\n");
printf("Child process id is: %d\n",(int)getpid());
printf("Parent process id is: %d\n",(int)getppid());
quicksort(a,0,n-1);
printf("Order of Sorted elements: ");
for(i=0;i<n;i++)
printf(" %d",a[i]);
printf("\n");
}
else if(pid<0){
printf("\n\nfork failed.....\n");
}
return 0;
}
void mergesort(int a[],int i,int j)
{
int mid;
if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid); //left recursion
mergesort(a,mid+1,j); //right recursion
merge(a,i,mid,mid+1,j); //merging of two sorted sub-arrays
}
}
void merge(int a[],int i1,int j1,int i2,int j2)
{
int temp[50]; //array used for merging
int i,j,k;
i=i1; //beginning of the first list
j=i2; //beginning of the second list
k=0;
while(i<=j1 && j<=j2) //while elements in both lists
{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while(i<=j1) //copy remaining elements of the first list
temp[k++]=a[i++];
while(j<=j2) //copy remaining elements of the second list
temp[k++]=a[j++];
//Transfer elements from temp[] back to a[]
for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j];
}
***********************************
2B
1)#include <stdio.h>
#include<string.h>
#include<stdlib.h>
void binary_search();
int a[50], n, item, loc, beg, mid, end, i;
void main(int argc,char *argv[])
{
n= atoi(argv[1]);
printf("n=%d",n);
for(i=0;i<n;i++)
{
a[i]= atoi(argv[i+2]);
}
printf("\nEnter ITEM to be searched: ");
scanf("%d", &item);
binary_search();
exit(EXIT_SUCCESS);
}
void binary_search()
{
beg = 0;
end = n-1;
mid = (beg + end) / 2;
while ((beg<=end) && (a[mid]!=item))
{
if (item < a[mid])
end = mid - 1;
else
beg = mid + 1;
mid = (beg + end) / 2;
}
if (a[mid] == item)
printf("\n\nITEM found at location %d\n", mid+1);
else
printf("\n\nITEM doesn't exist\n");
}
*******************************
2)
#include<stdio.h>
#include<sys/types.h>
#include<string.h>
#include<stdlib.h>
void bubble_sort(int[], int);
int main(int argc,char *argv[]) {
char *en[]={NULL};
char * carray[10], *ch;
pid_t pid;int n=5;
int arr[30], num, i;
printf("\nEnter no of elements :");
scanf("%d", &num);
printf("\nEnter array elements :");
for (i = 0; i < num; i++)
scanf("%d", &arr[i]);
bubble_sort(arr, num);
char c1[sizeof(int)];
snprintf(c1,sizeof(int),"%d",n);
ch=malloc(sizeof(c1));
strcpy(ch,c1);
for(i=0;i<n;i++)
{
char c[sizeof(int)];
snprintf(c,sizeof(int),"%d",arr[i]);
carray[i]=malloc(sizeof(c));
strcpy(carray[i],c);
}
char *newargv[]={NULL,NULL,NULL,NULL};
newargv[0]=argv[1];
newargv[1]=ch;
int j=2;
for(i=0;i<n;i++)
{
newargv[j]=carray[i];
j++;
}
pid=fork();
if(pid==0)
{
execve(argv[1],newargv,en);
exit(EXIT_FAILURE);
}
else if(pid>0)
{
printf("\nparent is executing\n");
wait();
}
else if(pid<0)
{
printf("\n Fork cannot be created");
}
return(0);
}
void bubble_sort(int iarr[], int num) {
int i, j, k, temp;
printf("\nUnsorted Data:");
for (k = 0; k < num; k++) {
printf("%5d", iarr[k]);
}
for (i = 1; i < num; i++) {
for (j = 0; j < num - 1; j++) {
if (iarr[j] > iarr[j + 1]) {
temp = iarr[j];
iarr[j] = iarr[j + 1];
iarr[j + 1] = temp;
}
}
printf("\nAfter pass %d : ", i);
for (k = 0; k < num; k++) {
printf("%5d", iarr[k]);
}
}
}
*******************
3.thread
# include <stdio.h>
# include <pthread.h>
int A[10][10];
int B[10][10];
int C[10][10];
#define SIZE 10
int r1,c1,r2,c2;
void *multiply(void* para);
typedef struct values {
int tid;//Thread Id //
int val1,val2;
int mult;
} values;
void accept_matrix(int M[SIZE][SIZE], int rows, int cols)
{
int i, j;
printf("\nEnter values in matrix:\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
scanf("%d",&M[i][j]);
}
}
}
void display_matrix(int M[SIZE][SIZE], int rows, int cols)
{
int i, j;
printf("\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
printf("%2d ",M[i][j]);
}
printf("\n");
}
}
int main()
{
pthread_t tid[1000]; //Max No. of Thread //
int i,j,k,l;
int *mult=0;
values v;
printf("Enter Number of Rows For Matrix 1 :");
scanf("%d",&r1);
printf("Enter Number of Columns For Matrix 1 :");
scanf("%d",&c1);
accept_matrix(A, r1,c1);
printf("\n");
printf("Enter Numer of Rows For Matrix 2 :");
scanf("%d",&r2);
printf("Enter Number of Columns For Matrix 2 :");
scanf("%d",&c2);
accept_matrix(B, r2,c2);
if(c1!=r2)
{
printf("Multipication of Matrix not Possible !!!");
}
else
{
for(i=0;i<r1;i=i+2)
{
for(j=0;j<c2;j=j+2)
{
C[i][j]=0;
}
}
v.val1=v.val2=v.mult=0;
l=0;
for(i=0;i<r1;i=i+1)
{
for(j=0;j<c2;j++)
{
for(k=0;k<c1;k++)
{
v.val1=v.val2=v.mult=0;
v.tid=l++;
v.val1 = A[i][k];
v.val2 = B[k][j];
pthread_create(&tid[l],NULL,multiply,&v);
// int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *),void *arg)
// creates thread and run the program concerrently returns 0 on sucess and garbage on failure
pthread_join(tid[l],(void**)&mult); //waits for the thread specified by 'thread' to terminate
// syntax: int pthread_join(pthread_t thread, void ** ret_val)
printf(" %d",mult);
sleep(2);
C[i][j]=C[i][j]+(int)mult;
}
}
}
}
printf("\nMatrix A:");
display_matrix(A, r1, c1);
printf("\nMatrix B:");
display_matrix(B, r2, c2);
printf("\n Multipication of Matrix ...\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("%d \t",C[i][j]);
}
printf("\n");
}
return 0;
}
void *multiply(void* para)
{
values *v = (values*)para;
v->mult = v->val1*v->val2;
printf("\nFinishing thread %d\t",v->tid);
printf("thread finished ... %u\n",(unsigned int)pthread_self()); //returns id of thread which is invoked
pthread_exit((void*)v->mult); //terminates the calling thread and returns a value which is
//available to another thread in the same process that calls pthread_join()
//syntax: void pthread_exit(void *ret_val)
}
*************************************************************
4.mutex
#include <stdio.h>
#include <pthread.h>
#define MAX 10 /* Numbers to produce */
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;//condp=1
int buffer = 0;
void producer(void *ptr) {
int i;
for (i = 1; i <= MAX; i++) {
while (buffer != 0) /* If there is something in the buffer then wait */
{ pthread_cond_wait(&condp, &the_mutex); }//condp=0
buffer = i;
printf("Producer is producing.....%d\n",buffer);
pthread_cond_signal(&condc); /* wake up consumer */
pthread_mutex_unlock(&the_mutex); /* release the buffer */
}
pthread_exit(0);
}
void consumer(void *ptr) {
int i;
for (i = 1; i <= MAX; i++) {
pthread_mutex_lock(&the_mutex); /* protect buffer */
while (buffer == 0) /* If there is nothing in the buffer then wait */
{ pthread_cond_wait(&condc, &the_mutex); }
printf("Consumer is consuming.....%d\n",buffer);
buffer = 0;
pthread_cond_signal(&condp); /* wake up producer */
pthread_mutex_unlock(&the_mutex); /* release the buffer */
}
pthread_exit(0);
}
int main(int argc, char **argv) {
pthread_t pro, con;
// Initialize the mutex and condition variables
pthread_mutex_init(&the_mutex, NULL);
pthread_cond_init(&condc, NULL); /* Initialize consumer condition variable */
pthread_cond_init(&condp, NULL); /* Initialize producer condition variable */
// Create the threads
pthread_create(&con, NULL, (void*)consumer, NULL);
pthread_create(&pro, NULL, (void*)producer, NULL);
pthread_join(con, NULL);
pthread_join(pro, NULL);
pthread_mutex_destroy(&the_mutex); /* Free up the_mutex */
pthread_cond_destroy(&condc); /* Free up consumer condition variable */
pthread_cond_destroy(&condp); /* Free up producer condition variable */
pthread_kill(con);
pthread_kill(pro);
}
***********************
sema
#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
#include<stdlib.h>
#define size 5
int buffer[size],counter;
sem_t available;
sem_t occupied;
sem_t mutex;
void initialize()
{
//sem_init(sem_t semaphore,);
sem_init(&available,0,size);
sem_init(&occupied,0,0);
sem_init(&mutex,0,1);
counter=1;
}
void *producer()
{
int val=0,i=0;
while(1){
sem_getvalue(&available,&val);
if(val==0)
printf("Buffer overflow....producer have to wait.....\n\n");
sem_wait(&available);//4
sem_wait(&mutex);//0
buffer[i%size]=counter;
printf("producer has produced %d...\n",counter);
sleep(2);
counter++;i++;
sem_post(&mutex);//1
sem_post(&occupied);//1
}
pthread_exit((void *)0);
}
void *consumer()
{
int val=0,i=0;
while(1){
sem_getvalue(&occupied,&val);
if(val==0)
printf("Buffer underflow...consumer have to wait...\n\n");
sem_wait(&occupied);//0
sem_wait(&mutex);//0
printf("consumer has consumed %d...\n",buffer[i%size]);
buffer[i%size]=0;
sleep(2);
i++;
sem_post(&mutex);//1
sem_post(&available);//5
}
pthread_exit((void *)0);
}
int main()
{
pthread_t producer_thread1,consumer_thread;
//pthread_t producer_thread2;
initialize();
pthread_create(&consumer_thread,NULL,consumer,NULL);
pthread_create(&producer_thread1,NULL,producer,NULL);
//pthread_create(&producer_thread2,NULL,producer,NULL);
pthread_join(producer_thread1,NULL);
//pthread_join(producer_thread2,NULL);
pthread_join(consumer_thread,NULL);
pthread_kill(producer_thread1);
//pthread_kill(producer_thread2);
pthread_kill(consumer_thread);
return 0;
}
********************************************
5.reader writer
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
pthread_mutex_t x,wsem;
pthread_t tid;
int readcount,writecount;
void initialize()
{
pthread_mutex_init(&x,NULL);
pthread_mutex_init(&wsem,NULL);
readcount=0;writecount=0;
}
void *reader(void *param)
{
int waittime;
waittime=rand()%5;
printf("\n reader is waiting to enter");
pthread_mutex_lock(&x);
readcount++;
if(readcount==1)
pthread_mutex_lock(&wsem);
printf("\n %d reader is inside",readcount);
pthread_mutex_unlock(&x);
sleep(waittime);
pthread_mutex_lock(&x);
readcount--;
if(readcount==0)
pthread_mutex_unlock(&wsem);
pthread_mutex_unlock(&x);
printf("\n reader is leaving");
}
void *writer(void *param)
{
int waittime;
waittime=rand()%3;
printf("\n writer is waiting to enter");
pthread_mutex_lock(&wsem);
writecount++;
printf("\n %d writer has entered",writecount);
sleep(waittime);
pthread_mutex_unlock(&wsem);
printf("\n %d writer is leaving",writecount);
sleep(30);
exit(0);
}
int main()
{
int n1,n2,i;
initialize();
printf("\n enter no. of readers:");
scanf("%d",&n1);
printf("\n enter the no. of writer:");
scanf("%d",&n2);
for(i=0;i<n1;i++)
pthread_create(&tid,NULL,reader,NULL);
for(i=0;i<n2;i++)
pthread_create(&tid,NULL,writer,NULL);
sleep(3);
printf("\n");
exit(0);
return 0;
}
*************************************************
6.dining
#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
#define N 5
#define thinking 1
#define hungry 2
#define eating 3
#define LEFT (ph_num + 4) % N
#define RIGHT (ph_num + 1) % N
int state[N];
int phil_num[N]={0,1,2,3,4};
sem_t lock;
sem_t S[N];
void test(int ph_num)
{
if(state[ph_num]==hungry &&
state[LEFT]!=eating && state[RIGHT]!=eating)
{
state[ph_num]=eating;
sleep(5);
printf("Philosopher %d takes fork %d and %d\n",ph_num+1, LEFT+1, ph_num+1);
printf("Philosopher %d is Eating\n\n", ph_num+1);
}
}
void take_fork(int ph_num)
{
sem_wait(&lock);
state[ph_num]=hungry;
printf("philosopher %d is hungry\n",ph_num);
test(ph_num);
sem_post(&lock);
sleep(2);
}
void put_fork(int ph_num)
{
sem_wait(&lock);
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\n", ph_num + 1);
test(LEFT);
test(RIGHT);
sem_post(&lock);
}
void *philosopher(void *num)
{
while(1)
{
int *i=num;
sleep(1);
take_fork(*i);
sleep(1);
put_fork(*i);
}
}
int main()
{
int i;
pthread_t thread_id[N];
sem_init(&lock, 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,philosopher, &phil_num[i]);
printf("Philosopher %d is thinking\n", i + 1);
}
for (i = 0; i < N; i++)
pthread_join(thread_id[i], NULL);
return 0;
}
********************************************
7.fifo
1)
#include<stdio.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<unistd.h>
#include<string.h>
#define MAX_BUF 80
int main(){
int fd,i = 0;
char *myfifo="/tmp/myfifo";
char str[MAX_BUF]="";
char ch;
mkfifo(myfifo,0666);
printf("\nEnter a string : ");
fgets(str,MAX_BUF,stdin);
fd=open(myfifo,O_WRONLY);
write(fd,str,strlen(str));
close(fd);
unlink(myfifo);
return 0;
}
2)
#include<stdio.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<unistd.h>
#include<string.h>
#define MAX_BUF 1024
int main()
{
int fd,k,i, c=0,c1=0;
char *myfifo="/tmp/myfifo";
char str[MAX_BUF]="";
mkfifo(myfifo,0666);
fd=open(myfifo,O_RDONLY);
read(fd,str,sizeof(str));
printf("\nReceived Messaged= %s\n",str);
k=strlen(str)-1;
printf("length = %d\n",k);
for(i=0;str[i]!='\0';i++)
if(str[i]==' ')
c++;
for(i=0;str[i]!='\0';i++)
if(str[i]=='\n')
c1++;
printf("\n\nTotal lines are %d\n",c1);
printf("\n\nTotal words are %d\n ",c+1);
close(fd);
return 0;
}
***************************************************
PIPE
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
int main()
{
int fd1[2],fd2[2],nbytes;
pid_t childpid;
char str[]="/root/Desktop/Welcome";
FILE *fp;
char readbuffer[100],buffer[200]="",filebuf[20];
pipe(fd1);
pipe(fd2);
printf("pipe created...\n");
if((childpid=fork())==1)
{
perror("fork");
exit( 1);
}
//childpid = fork();
if(childpid==0) //child process
{
//reads the content of file on first pipe
close(fd1[1]);
nbytes=read(fd1[0],readbuffer,sizeof(readbuffer));
printf("\nfile path: %s\n",readbuffer);
fp=fopen(readbuffer,"r");
while(!feof(fp))
{
if(fgets(filebuf,strlen(filebuf)+1,fp)!=NULL)
{strcat(buffer,filebuf);}
}
//writes the contents of the file on second pipe
close(fd2[0]);
printf("\nChild writes the contents of file on second pipe:\n");
printf("%s\n",buffer);
write(fd2[1],buffer,strlen(buffer)+1);
exit(0);
}
else { //parent process
//writes a pathname of file on first pipe
close(fd1[0]);
write(fd1[1],str,strlen(str)+1);
// close(fd1[1]);
//reads the contents of file on second pipe
sleep(2);
close(fd2[1]);
nbytes=read(fd2[0],readbuffer,sizeof(readbuffer));
printf("\nParent reads the contents of file on second pipe:\n");
puts(readbuffer);
}
return 0;
}
-***************************************
8.
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include<stdio.h>
#include<string.h>
int main()
{
int retval,shmid;
void *memory=NULL;
char *p;
// Initialization of shared memory
shmid=shmget((key_t)123456789,6,IPC_CREAT|0666);
if(shmid<0)
{
printf("Failure in creation ");
shmid=shmget((key_t)123456789,6,0666);
}
printf("\n We are getting the shared memory created %d \n",shmid);
// Attachment to shared memory
memory=shmat(shmid,NULL,0);
if(memory==NULL)
{
printf("\n Attachment failure");
return 0;
}
p=(char *)memory;
memset(p,'\0',6);
memcpy(p,"hello",6);
retval=shmdt(p);
if(retval<0)
{
printf("Suffered detachment");
return 0;
}
}
/**OUTPUT
[student@localhost Downloads]$ gcc shmwrite.c
[student@localhost Downloads]$ ./a.out
We are getting the shared memory created 1835015
[student@localhost Downloads]$
*/
****************************************************
9.
Comments
Post a Comment