Sei sulla pagina 1di 22

/*

=======================================================================
Problem Statement
: Process control system calls: The demonstration of for
k, execve and
wait system calls along with zombie and orphan states
a. Implement the C program in which main program accepts the integers to
be sorted. Main program uses the fork system call to create a new process
called a child process. Parent process sorts the integers using merge sort
and waits for child process using wait system call to sort the integers usin
g
quick sort. Also demonstrate zombie and orphan state.
=======================================================================
*/
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void quicksort(int [10],int,int);
void main()
{
int pid, ppid, a[10], size, i;
printf("\nPARENT: My process-id is %d.", getpid());
printf("\n\nEnter the number of elements in the array: ");
scanf("%d", &size);
printf("Enter %d elements: ", size);
for(i=0;i<size;i++)
scanf("%d",&a[i]);
printf("\nForking now!\n");
pid = fork(); //Here, the child process is created and both child & parent run
//simultaneously. fork() returns 0 to child
process and pid of //child to parent process.
So, if int pid here is 0, it means we //are in
child process and if any +ve no., then in parent process
//where the +ve no. is the child's pid.
if(pid==0)
{
printf("\nCHILD: My process-id is %d.", getpid());
printf("\nCHILD: My parent's process-id is %d.", getppid());
quicksort(a, 0, size-1);
printf("\nSorted elements: ");
for(i=0;i<size;i++)
printf(" %d",a[i]);printf("\nCHILD: I am dying now");
printf("\n-------------------------------------------------------");
/* ORPHAN
printf("\nCHILD: I am sleeping now.");
sleep(10);
printf("\n-------------------------------------------------------\n\n");
system("ps -elf | grep a.out");*/
// ZOMBIE
printf("\nCHILD: I am dying now");
printf("\n-------------------------------------------------------\n\n");
system("ps -elf | grep a.out");
exit(0);
}
else if (pid>0)
{
system("wait");
printf("\nPARENT: I am back. ");

printf("\nPARENT: My process-id is %d.", getpid());


printf("\nPARENT: My child's process-id is %d.", pid);
quicksort(a, 0, size-1);
printf("\nSorted elements: ");
for(i=0;i<size;i++)
printf(" %d",a[i]);
printf("\nPARENT: I am dying now.");
printf("\n-------------------------------------------------------");
/* ORPHAN
system("ps -elf | grep a.out");
exit(0);*/
// ZOMBIE
printf("\nPARENT: I am sleeping now.");
sleep(10);
printf("\n-------------------------------------------------------\n");
system("ps -elf | grep a.out");
}
}
void quicksort(int a[10],int first,int last)
{
int pivot,j,temp,i;
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j){
while(a[i]<=a[pivot]&&i<last)
i++;
while(a[j]>a[pivot])
j--;
if(i<j){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[pivot];
a[pivot]=a[j];
a[j]=temp;
quicksort(a,first,j-1);
quicksort(a,j+1,last);
}
}
/*
====================================OUTPUT============================
========
pict@ubuntu:~/3807/Final$ gcc a_forkandsort.c
pict@ubuntu:~/3807/Final$ ./a.out
PARENT: My process-id is 2932.
Enter the number of elements in the array: 4
Enter 4 elements:
56
12
388
92
Forking now!
CHILD: My process-id is 2934.
CHILD: My parent's process-id is 2932.
Sorted elements: 12 56 92 388
CHILD: I am dying now

------------------------------------------------------PARENT: I am back.
PARENT: My process-id is 2932.
PARENT: My child's process-id is 2934.
Sorted elements: 12 56 92 388
PARENT: I am dying now.
------------------------------------------------------pict@ubuntu:~/3807/Final$
ORPHAN:
====================================OUTPUT====================================
pict@ubuntu:~/3807/Final$ gcc a_orphan.c
pict@ubuntu:~/3807/Final$ ./a.out
PARENT: My process-id is 2949.
Forking now!
PARENT: I am back.
PARENT: My process-id is 2949.
PARENT: My child's process-id is 2950.
PARENT: I am dying now
------------------------------------------------------CHILD: My process-id is 2950.
CHILD: My parent's process-id is 2949.
0 S pict
2949 2693 0 80 0 - 507 wait 12:37 pts/11 00:00:00 ./a.o
ut
1 S pict
2950 2949 0 80 0 - 507 hrtime 12:37 pts/11 00:00:00 ./a.o
ut
0 S pict
2951 2949 0 80 0 - 567 wait 12:37 pts/11 00:00:00 sh -c
ps -elf | grep a.out
0 S pict
2953 2951 0 80 0 - 1170 pipe_w 12:37 pts/11 00:00:00 grep
a.out
pict@ubuntu:~/3807/Final$ CHILD: I am sleeping now.
------------------------------------------------------1 S pict
2950 1852 0 80 0 - 507 wait 12:37 pts/11 00:00:00 ./a.o
ut
0 S pict
2955 2950 0 80 0 - 567 wait 12:37 pts/11 00:00:00 sh -c
ps -elf | grep a.out
0 S pict
2957 2955 0 80 0 - 1170 pipe_w 12:37 pts/11 00:00:00 grep
a.out
pict@ubuntu:~/3807/Final$
ZOMBIE:
gcc a_zombie.c
amar@Amar-Dell-System-Inspiron-5420:~/Final$ ./a.out
PARENT: My process-id is 2480.
Forking now!
PARENT: I am back.
PARENT: My process-id is 2480.
PARENT: My child's process-id is 2481.
CHILD: My process-id is 2481.
CHILD: My parent's process-id is 2480.
CHILD: I am dying now
------------------------------------------------------0 S amar
2480 2395 0 80 0 - 1049 hrtime 13:21 pts/0
00:00:00 ./a.o
ut
1 S amar
2481 2480 0 80 0 - 1049 wait 13:21 pts/0
00:00:00 ./a.o
ut
0 S amar
2482 2481 0 80 0 - 1111 wait 13:21 pts/0
00:00:00 sh -c
ps -elf | grep a.out
0 S amar
2484 2482 0 80 0 - 3985 pipe_w 13:21 pts/0
00:00:00 grep
a.out
PARENT: I am sleeping now.
-------------------------------------------------------

0 S amar
2480 2395 0 80 0 - 1049 wait 13:21 pts/0
00:00:00 ./a.o
ut1 Z amar
2481 2480 0 80 0 0 exit 13:21 pts/0
00:00:00 [a.
out] <defunct>
0 S amar
2486 2480 0 80 0 - 1111 wait 13:21 pts/0
00:00:00 sh -c
ps -elf | grep a.out
0 S amar
2488 2486 0 80 0 - 3985 pipe_w 13:21 pts/0
00:00:00 grep
*//*
=======================================================================
Name
: b_execv.c
Problem Statement : Process control system calls: The demonstration of fork,
execve and
wait system calls along with zombie and orphan states.
b. Implement the C program in which main program accepts an integer
array. Main program uses the fork system call to create a new process
called a child process. Parent process sorts an integer array and passes t
he
sorted array to child process through the command line argumen
ts of
execve system call. The child process uses execve system call to load new
program that uses this sorted array for performing the binary search to
search the particular item in the array.
=======================================================================
*/
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void quicksort(int [10],int,int);
void main()
{
int pid, ppid, a[10], size, i;
char *argv[12];
for(i=0; i<12; i++)
{
argv[i] = (char *) malloc(20);
}
printf("\nIn the main of parent process. \nMy process-id is %d.", getpid());
printf("\n\nEnter the number of elements in the array: \n");
scanf("%d", &size);
printf("Enter %d elements: ", size);
for(i=0;i<size;i++)
scanf("%d",&a[i]);
quicksort(a, 0, size-1);
printf("Sorted elements: ");
for(i=0;i<size;i++)
printf(" %d",a[i]);
printf("\nPARENT: I am calling my child for searching now!\n");
printf("-------------------------------------------------------");
pid = vfork(); //Here, the child process is created and both
child & parent run//simultaneously. fork() returns 0
to child process and pid of
//child to parent process. So, if int
pid here is 0, it means we
//are in child process and if any
+ve no., then in parent process
//where the +ve no. is the child's
pid.
if(pid==0)
{

printf("CHILD: In child process. My process-id is %d.\n", getpid());


printf("CHILD: My parent's process-id is %d.\n\n", getppid());
printf("\nCHILD: Calling searching program using execv now. I will be
overlayed!\n");
for(i=0; i<size; i++){
sprintf(argv[i+1], "%d", a[i]);
}
argv[0] = "./b_binarysearch";
argv[size+2] = NULL;
execv("./b_binarysearch", argv);
printf("Error");
printf("\nCHILD: I am dying now\n");
printf("-------------------------------------------------------\n\n");
}
else if (pid>0)
{
system("wait");
printf("\nPARENT: I am dying now\n");
printf("-------------------------------------------------------");
printf("\n\n.");
}
}
void quicksort(int a[10],int first,int last)
{
int pivot,j,temp,i;
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j){
while(a[i]<=a[pivot]&&i<last)
i++;
while(a[j]>a[pivot])
j--;
if(i<j){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[pivot];
a[pivot]=a[j];
a[j]=temp;
quicksort(a,first,j-1);
quicksort(a,j+1,last);
}
}
/*========================BINARY SEARCH PROGRAM======================
Name
: b_binarysearch.c
=====================================================================*/
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void binarysearch(long int [10], int n);
void main(int argc, char *argv[],char *envp[])
{

int i, n=0;
long ret[10];
for(i=1; argv[i]!=NULL; i++)
{
ret[i] = strtol(argv[i], NULL, 10);
n++;
}
printf("SEARCH: In second child process. My process-id is %d.\n", getpid());
printf("SEARCH: My parent's process-id is %d.\n\n", getppid());
binarysearch(ret, n);
}
void binarysearch(long int a[10], int n)
{
int c, first, last, middle, search;
printf("Enter value to search: \n");
scanf("%d",&search);
printf("\n\n=================In Binary Search Program===================\n");
first = 0;
last = n - 1;
middle = (first+last)/2;
while( first <= last )
{
if ( a[middle] < search )
first = middle + 1;
else if ( a[middle] == search )
{
printf("%d found at location %d.\n", search, middle);
break;}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
printf("%d is not present in the list.\n", search);
}
/*================================OUTPUT==============================
pict@ubuntu:~/3807/Final$ gcc b_binarysearch.c -o b_binarysearch
pict@ubuntu:~/3807/Final$ gcc b_execv.c
pict@ubuntu:~/3807/Final$ ./a.out
In the main of parent process.
My process-id is 3006.
Enter the number of elements in the array:
5
Enter 5 elements:
3
6
9
8
4
Sorted elements: 3 4 6 8 9
PARENT: I am calling my child for searching now!
------------------------------------------------------CHILD: In child process. My process-id is 3007.
CHILD: My parent's process-id is 3006.
CHILD: Calling searching program using execv now. I will be overlayed!
SEARCH: In second child process. My process-id is 3007.
SEARCH: My parent's process-id is 3006.
Enter value to search:
PARENT: I am dying now

------------------------------------------------------.pict@ubuntu:~/3807/Final$
9
=================In Binary Search Program===================
9 found at location 5.
pict@ubuntu:~/3807/Final$
*//*
=======================================================================
Name
: matrixthread.c
Problem Statement : Thread management using pthread library.
Implement matrix multiplication using multithreading. Application shoul
d
have pthread_create, pthread_join, pthread_exit. In the program, every
thread must return the value and must be collected in pthread_join in the
main function. Final sum of row-column multiplication must be done by
main thread (main function).
=======================================================================
*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int A[10][10],B[10][10],C[10][10];
int R1,C1,R2,C2;
struct v
{
int i; //row
int j; //column
int k;
};
void *runner(void *structure);
int main()
{
int k,i,n,j,sum=0;
printf("\nEnter the size of first matrix\n");
printf("\tRow :");
scanf("%d",&R1);
printf("\tColumn :");
scanf("%d",&C1);
printf("\nEnter the size of second matrix\n");
printf("\tRow :");
scanf("%d",&R2);
printf("\tColumn :");
scanf("%d",&C2);
printf("Enter the elements of first matrix: ");
for(i=0;i<R1;i++)
{
for(j=0;j<C1;j++)
{
scanf("%d",&A[i][j]);
}
}
printf("Enter the elements of second matrix: "); for(i=0;i<R2;i++)
{
for(j=0;j<C2;j++)
{
scanf("%d",&B[i][j]);
}
}

printf("\nFirst Matrix\n");
for(i=0;i<R1;i++)
{
printf("\n");
for(j=0;j<C1;j++)
printf("%d\t",A[i][j]);
}
printf("\nSecond Matrix\n");
for(i=0;i<R2;i++)
{
printf("\n");
for(j=0;j<C2;j++)
printf("%d\t",B[i][j]);
}
void *thread_result;
for(i = 0; i < R1; i++)
{
for(j = 0; j < C2; j++)
{
for(n = 0; n< C1; n++)
{
//Assign a row and column for each thread
struct v *data = (struct v *) malloc(sizeof(struct v));
data->i = i;
data->j = j;
data->k = n;
// Now create the thread passing it data as a parameter
pthread_t tid;
//Thread ID
//Create the thread
pthread_create(&tid, NULL, runner, data);
//Make sure the parent waits for all thread to complete
pthread_join(tid, &thread_result);
C[i][j] += *((int *)thread_result);
}
}
}
printf("\nAfter multiplication using \n"); for(i=0;i<R1;i++)
{
printf("\n");
for(j=0;j<C2;j++)
printf("%d\t",C[i][j]);
}
return 0;
}
void *runner(void *structure)
{
struct v *data = structure; // the structure that holds our data
int n, *product; //the counter and sum
product=malloc(sizeof(int));
//Row multiplied by column
*product =A[data->i][data->k] * B[data->k][data->j];
//Exit the thread
pthread_exit((void*)product);
}
/
*======================================OUTPUT=========================

==========
amar@Amar-Dell-System-Inspiron-5420:~/zzzz$ gcc matrixthread.c -lpthread
amar@Amar-Dell-System-Inspiron-5420:~/zzzz$ ./a.out
Enter the size of first matrix
Row :3
Column :3
Enter the size of second matrix
Row :3
Column :3
Enter the elements of first matrix:
1
2
3
4
5
6
7
8
9
Enter the elements of second matrix:
1
1
11
1
1
1
1
1
First Matrix
1 2 3
4 5 6
7 8 9
Second Matrix
1 1 1
1 1 1
1 1 1
After multiplication using
6 6 6
15 15 15
24 24 24
*//*
=======================================================================
Name
: 3_mutex3807.c
Problem Statement : Thread synchronization using counting semaphores and mutu
al exclusion
using mutex : Application to demonstrate: producer-consumer problem with
counting semaphores and mutex.
=======================================================================
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include </usr/include/semaphore.h>
#include <unistd.h>
#define PROD 3
#define CONS 3
#define ITEMS 4
#define BUFFER_SIZE 5
typedef struct

{
int emptypos; //first empty position by [emptypos % BUFFER]
int fullpos; //first full position by [fullpos % BUFFER]
int buff[BUFFER_SIZE];
sem_t full; //number of filled spots
sem_t empty; //number of empty spots
pthread_mutex_t mymutex; //mutex for mutual exclusion of shared data in Buffer
}buffer;
buffer b1;
void *producer(void *prod)
{
int i, item, index;
index = (int)prod;
for(i=0; i<ITEMS; i++)
{
item = i;
sem_wait(&b1.empty); //Decrement empty slot count of buffer
pthread_mutex_lock(&b1.mymutex); //lock mutex before entering critical
section
//critical section begins
b1.buff[b1.emptypos] = item;
b1.emptypos = (b1.emptypos+1)%BUFFER_SIZE;printf("Producer [%d] = I produced %d
\n", index, item);
fflush(stdout);
//critical section ends
pthread_mutex_unlock(&b1.mymutex); //unlock mutex while leaving critical
section
sem_post(&b1.full); //Increment full slot count of buffer
}
return NULL;
}
void *consumer(void *cons)
{
int i, item, index;
index = (int)cons;
for(i=ITEMS; i>0; i--)
{
sem_wait(&b1.full); //Decrement full slot count of buffer
pthread_mutex_lock(&b1.mymutex); //lock mutex before entering critical
section
item = i;
//critical section begins
item = b1.buff[b1.fullpos];
b1.fullpos = (b1.fullpos+1)%BUFFER_SIZE;
printf("Consumer [%d] = I consumed %d \n", index, item);
fflush(stdout);
//critical section ends
pthread_mutex_unlock(&b1.mymutex); //unlock mutex while leaving critical
section
sem_post(&b1.empty); //Increment empty slot count of buffer
}
return NULL;
}
int main()
{
pthread_t Pid, Cid;
int index;
sem_init(&b1.full, 0, 0); //(semaphore to be initialized, to share or not, defa
ult value)
sem_init(&b1.empty, 0, BUFFER_SIZE);

pthread_mutex_init(&b1.mymutex, NULL);for(index=0; index<PROD; index++)


{
pthread_create(&Pid, NULL, producer, (void*)index);
}
for(index=0; index<PROD; index++)
{
pthread_create(&Cid, NULL, consumer, (void*)index);
}
pthread_exit(NULL);
}
/*============================OUTPUT=============================
amar@Amar-Dell-System-Inspiron-5420:~$ ./a.out
Producer [0] = I produced 0
Producer [1] = I produced 0
Producer [2] = I produced 0
Consumer [2] = I consumed 0
Producer [1] = I produced 1
Consumer [0] = I consumed 0
Consumer [0] = I consumed 0
Producer [0] = I produced 1
Producer [0] = I produced 2
Consumer [2] = I consumed 1
Producer [1] = I produced 2
Consumer [0] = I consumed 1
Consumer [0] = I consumed 2
Producer [0] = I produced 3
Producer [2] = I produced 1
Producer [2] = I produced 2
Consumer [1] = I consumed 2
Producer [2] = I produced 3
Consumer [1] = I consumed 3
Consumer [1] = I consumed 1
Consumer [1] = I consumed 2
Producer [1] = I produced 3
Consumer [2] = I consumed 3
Consumer [2] = I consumed 3
amar@Amar-Dell-System-Inspiron-5420:~$ #include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
#define BUFFER_SIZE 20
void init();
void* consumer(void *arg);
void* producer(void *arg);
int item = 1;
typedef struct
{
int in;
int out;
int buff[BUFFER_SIZE];
sem_t empty;
sem_t full;
pthread_mutex_t buff_lock;
}buffer;
buffer b;
int main(void)

{
int np, nc, i;
pthread_t Pid[5], Cid[5];
init();
printf("\nEnter the number of Producers (max 5): ");
scanf("%d", &np);
printf("\nEnter the number of Consumers (max 5): ");
scanf("%d", &nc);
for(i=0; i<np; i++)
{
int *arg = malloc (sizeof(int*));
*arg = i;
pthread_create(&Pid[i], NULL, producer, arg);
printf("\n\nProducer thread %d created", i);
}
for(i=0; i<nc; i++)
{
int *arg = malloc (sizeof(int*));
*arg = i;
pthread_create(&Cid[i], NULL, consumer, arg);
printf("\n\nConsumer thread %d created", i);
}
for(i=0; i<np; i++)
{
printf("\n\nProducer thread %d created", i);
pthread_join(Pid[i], NULL);
}
for(i=0; i<nc; i++)
{
printf("\n\nConsumer thread %d created", i);
pthread_join(Cid[i], NULL);
}
return 0;
}
void init()
{
sem_init(&b.empty, 0, BUFFER_SIZE);
sem_init(&b.full, 0, 0);
pthread_mutex_init(&b.buff_lock, NULL);
b.in = 0;
b.out = 0;
}
void* producer(void *arg)
{
int i = *(int *)arg;
while(1)
{
sem_wait(&b.empty);
pthread_mutex_lock(&b.buff_lock);
printf("\nProducer %d has produced item number %d (|)", i+1,
item);
b.buff[(b.in++)%BUFFER_SIZE] = item++;
pthread_mutex_unlock(&b.buff_lock);

sem_post(&b.full);
sleep(10);
}
}
void* consumer(void *arg)
{
int i = *(int *)arg;
while(1)
{
sem_wait(&b.full);
pthread_mutex_lock(&b.buff_lock);
printf("\nConsumer %d has consumed item number %d (x)", i+1,
b.buff[(b.out++)%BUFFER_SIZE]);
pthread_mutex_unlock(&b.buff_lock);
sem_post(&b.empty);
sleep(10);
}
}
/*
=======================================================================
Name
: 4_mutex_cv.c
Problem Statement : Deadlock Avoidance Using Semaphores:
Implement the deadlock-free solution to Dining Philosophers problem to
illustrate the problem of deadlock and/or starvation that can occur when
many synchronized threads are competing for limited resources.
=======================================================================
*/
#include<stdio.h>
#include<stdlib.h>
#include<semaphore.h>
#include<pthread.h>
sem_t cs[5];
int n;
void* philosopher(void* i);
void putdown(int i);
void pickup(int i);
void test(int i);
enum status {hungry=1,thinking,eating};
typedef struct {
pthread_mutex_t mon;
pthread_cond_t cv[5];
enum status state[5];
}phil_struct;
phil_struct ps;
int main()
{
int i;
int result;
void *res;
//pthread_t *phil;
//printf("ENTER NO OF PHILOSOPHERS:");
//scanf("%d",&n);
//cs=malloc(n*sizeof(sem_t));
//phil=malloc(n*sizeof(pthread_t));
n=5;
pthread_t phil[5];

for(i=0;i<n;i++)
sem_init(&cs[i],0,1);
for(i=0;i<n;i++)
{//printf("creating..\n ");
result=pthread_create(&phil[i],NULL,philosopher,(void*)i);
if(result!=0)
{
printf("error creating thread\n");
exit(0);
}
}
for(i=0;i<5;i++)
{
pthread_join(phil[i],&res);
}
return 0;
}
void* philosopher(void* i)
{
int *ph;
ph=(int *)i;
//printf("IN PHILOSOPHER");
while(1)
{
printf("philosopher %d is hungry \n",ph);
pickup((int)ph);
sleep(rand()%9);
//sleep(rand()%9);
putdown((int)ph);
}
pthread_exit(NULL);
}
void pickup(int i)
{
ps.state[i]=hungry;
pthread_mutex_lock(&ps.mon);
test(i);
if(ps.state[i]!=eating)
pthread_cond_wait(&ps.cv[i],&ps.mon);
printf("phlosopher %d is eating \n",ph);
pthread_mutex_unlock(&ps.mon);
}
void putdown(int i)
{
ps.state[i]=thinking;
printf("philosopher %d is thinking\n",ph);
pthread_mutex_lock(&ps.mon);
test((i-1)%5);
test((i+1)%5);
pthread_mutex_unlock(&ps.mon);
}
void test(int i)
{
if(ps.state[i]==hungry && ps.state[(i-1)%5]!=eating && ps.state[(i+1)%5]!=eating
){
ps.state[i]=eating;
pthread_cond_signal(ps.cv);
}
}

/*========================OUTPUT============================
philosopher 0 is hungry
phlosopher 0 is eating
philosopher 1 is hungry
philosopher 2 is hungry
phlosopher 2 is eating
philosopher 3 is hungry
philosopher 4 is hungry
philosopher 0 is thinking
phlosopher 4 is eating
philosopher 4 is thinking
philosopher 2 is thinking
phlosopher 1 is eating
phlosopher 3 is eating
philosopher 3 is thinking
philosopher 1 is thinking
*//*
=======================================================================
Name
: 5a_PIPE.c
Problem Statement : Inter process communication in Linux using following.
a. Pipes: Full duplex communication between parent and child processes.
Parent process writes a pathname of a file (the contents of the file
are desired) on one pipe to be read by child process and child
process writes the contents of the file on second pipe to be read by
parent process and displays on the standard output.
=======================================================================
*/
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* read_from_pipe1 (int file);
void read_from_pipe2 (int file);
void write_to_pipe1 (int file);
void write_to_pipe2 (int file, FILE* fp);
int main (void)
{
pid_t pid;
int mypipe[2], pipe2[2];
char *path;
FILE *fp;
if (pipe (mypipe)) //Pipe returns -1 on failure
{
fprintf (stderr, "Pipe failed.\n");
return EXIT_FAILURE;
}
if (pipe (pipe2)) //Pipe returns -1 on failure
{
fprintf (stderr, "Pipe failed.\n");
return EXIT_FAILURE;
}
pid = fork ();
if (pid == (pid_t) 0) //This is the child process.
{
close (mypipe[1]);
path = read_from_pipe1 (mypipe[0]);
fp = fopen(path, "r");

close (pipe2[0]);
write_to_pipe2 (pipe2[1], fp);
return EXIT_SUCCESS;}
else //This is the parent
process.
{
close (mypipe[0]);
write_to_pipe1 (mypipe[1]);
close (pipe2[1]);
read_from_pipe2 (pipe2[0]);
return EXIT_SUCCESS;
}
return 0;
}
char* read_from_pipe1 (int file) // Read filename from the pipe and open
the file
{
FILE *stream;
char *pathname = malloc(100*sizeof(char));
stream = fdopen (file, "r");
fscanf(stream,"%s",pathname);
pathname[strlen(pathname)] = '\0';
fclose(stream);
return pathname;
}
void write_to_pipe1 (int file) // Write path of the file to the pipe 1
{
FILE *stream;
stream = fdopen (file, "w");
fprintf (stream, "testfile.txt");
fclose (stream);
}
void read_from_pipe2 (int file) // Read from the pipe and print to
terminal
{
FILE *stream;
int c;
stream = fdopen (file, "r");
while ((c = fgetc (stream)) != EOF)
putchar (c);
fclose (stream);
}
void write_to_pipe2 (int file, FILE* fp) // Write text from testfile to the pipe
.
{
FILE *stream;int c;
stream = fdopen(file, "w");
while((c = fgetc(fp)) != EOF)
fprintf(stream, "%c", c);
fclose(stream);
}
/*
====================================OUTPUT============================
========
[admin@localhost 3807]$ gcc 5a.c
[admin@localhost 3807]$ ./a.out
This is the testfile that is being printed by Amar's code using PIPE.
*//*
=======================================================================

Name
: 5b_FIFO_1.c
Author
: Amar Chandole
Roll No. : 3807
Problem Statement : Inter process communication in Linux using following.
b. FIFOs: Full duplex communication between two independent processes.
First process accepts sentences and writes on one pipe to be read by
second process and second process counts number of characters, number
of words and number of lines in accepted sentences, writes this output in
a text file and writes the contents of the file on second pipe to be read
by
first process and displays on standard output.
Flow : This is server side code. Create 2 FIFOs, open 1 in read mode & other in
write. Take input from user on server side from user and write it on FIFO
using write function. Same FIFO is to be opened on Client side using read,
processed and stats are sent back here.
=======================================================================
*/
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
int main (void)
{
int i=0, fd1, fd2, num;
char input[1000], output[1000], c; //buffer for input sentences
mkfifo("amarfifo1",0644); //create FIFO 1
fd1=open("amarfifo1",O_WRONLY); //O_WRONLY Open in write only mode
mkfifo("amarfifo2",0644); //create FIFO 2
fd2=open("amarfifo2",O_RDONLY); //O_WRONLY Open in read only mode
printf("\nReady to broadcast to client\n");
printf("Enter message : \n");
while((c=getc(stdin))!='`') //recieve sentences from user
until ` is pressed
input[i++] = c;
input[i]='\0';
write(fd1, input, strlen(input)); //write to FIFO
while((num=read(fd2,output,1000))>0) {
output[num]='\0';
printf("\nStats recieved from client: \n%s", output);
fflush(stdout);
break;
}
return;
}
/*
============================OUTPUT====================================
[admin@localhost ~]$ gcc 5b_1.c
[admin@localhost ~]$ ./a.out
Ready to broadcast to client

Enter message :
Hello, this is Amar on server side
Signing off
Bye`
Stats recieved from client:
Number of characters: 40
Number of words: 10
Number of lines: 3
[admin@localhost ~]$
*//*
=======================================================================
Name
: 5b_FIFO_2.c
Author
: Amar Chandole
Roll No. : 3807
Problem Statement : Inter process communication in Linux using following.
b. FIFOs: Full duplex communication between two independent processes.
First process accepts sentences and writes on one pipe to be read
second process and second process counts number of characters,
number of words and number of lines in accepted sentences, writes
this output in a text file and writes the contents of the file on second
pipe to be read by first process and displays on standard output.
Flow : This is client side code. Create 2 FIFOs, open FIFO1 in read mode & FIFO2
in write. Read input from FIFO1 here and calculate stats, write them in file.
Now read this file (use rewind(fp)) and write contents on FIFO 2 using write
function. Same FIFO is to be opened on Server side using read and stats are
to be printed.
=======================================================================
*/
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <ctype.h>
int main()
{
int fd1, fd2, num, i, no_lines=0, no_words=0, no_chars=0, c;
char input[1000];
char output[1000], a[100];
FILE* fp = fopen("stats.txt", "w+");
mkfifo("amarfifo1",0644);
fd1=open("amarfifo1", O_RDONLY);
mkfifo("amarfifo2",0644);
fd2=open("amarfifo2", O_WRONLY);
printf("\nReady to recieve from server\n");
while((num=read(fd1,input,1000))>0)
{
input[num]='\0';
printf("\nReceived from server (using FIFO 1): \n%s ", input);
fflush(stdout);
break;
}for(i=0; i<strlen(input); i++)
{
if(isalnum(input[i]))
no_chars++;

else if(isspace(input[i]))
no_words++;
if(input[i] == '\n')
no_lines++;
}
if(!isspace(input[strlen(input)]))
no_words++;
fprintf(fp, "Number of characters: %d", no_chars);
fprintf(fp, "\nNumber of words: %d", no_words);
fprintf(fp, "\nNumber of lines: %d\n", no_lines+1);
/* Can also be used by commenting previous part
printf(fp, "%s", input);
fclose(fp);
fp = fopen("stats.txt", "r");
system("wc -m stats.txt");
system("wc -w stats.txt");
system("wc -l stats.txt");
*/
printf("\nSending the stats to the server (using FIFO 2)\n\n");
rewind(fp);
for (i=0; fgets(a, sizeof(a), fp)!=NULL; i++)
strcat(output, a);
write(fd2,output,strlen(output)); //write to FIFO
write(fd1, "\n", 1);
fclose(fp);
return;
}
/*
=================================OUTPUT===============================
[admin@localhost ~]$ gcc 5b_2.c -o b
[admin@localhost ~]$ ./b
Ready to recieve from server
Received from server (using FIFO 1):
Hello, this is Amar on server side
Signing off
Bye
Sending the stats to the server (using FIFO 2)
=====================================================================
*//*
Name
: 5c.c
Author
: Amar Chandole
Roll No.
: 3807
Problem Statement : Signals: Detecting the termination of multiple child proces
sesImplement the C program to demonstrate the use of SIGCHLD
signal. A parent process Creates multiple child process (minimum th
ree child
processes). Parent process should be Sleeping until it creates the number of
child processes. Child processes send SIGCHLD signal to parent process to
interrupt from the sleep and force the parent to call wait for the Collection of
status of terminated child processes.
/
=====================================================================*
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <stdio.h>
void handle_sigchld(intsig)
{
pid_t pid;
int status;

while (1)
{
pid = waitpid(-1, &status, WNOHANG);
if (pid <= 0) // No more zombie children to reap.
break;
printf("Reaped child %d\n",pid);
}
sleep(1);
}
int main()
{
int i;
signal(SIGCHLD,handle_sigchld);
for (i= 0;i< 3;i++)
{
if (fork() == 0) //Child-process code.
{
printf("Hello from child %d\n",getpid());
sleep(5);
return 0;
//Terminate child
}
}
while (1) //Parent-process code.
sleep(2); //Wait for children
return 0; //to terminate.
}/*=================================OUTPUT===============================
amar@Amar-Dell-System-Inspiron-5420:~/Desktop/5c$ gcc 5c.c
amar@Amar-Dell-System-Inspiron-5420:~/Desktop/5c$ ./a.out
Hello from child 2436
Hello from child 2437
Hello from child 2438
Reaped child 2437
Reaped child 2436
Reaped child 2438
*/OUTPUT

#include<linux/module.h>
#include<linux/kernel.h>
int init_module(void)
{

printk(KERN_INFO "Wassup\n");
return 0;
}
void cleanup_module(void)
{
printk(KERN_INFO "clean up\n");
}
Makefile
obj-m += sumaiya.o
all:
make -C/lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C/lib/modules/$(shell uname -r)/build M=$(PWD) cleanOUTPUT#include <linux/
kernel.h>
asmlinkage long sys_hello(void)
{
printk(KERN_INFO "Hello World!\n");
return 0;
}
MAKEFILE::
obj-y := hello.o
PROGRAM ::
#include <stdio.h>
#include <linux/kernel.h>
#include <sys/syscall.h>
#include <unistd.h>
int main()
{
long int r = syscall(358);
printf("System call sys_hello returned %ld\n",r);
return 0;
}OUTPUT

/*
====================================================
Name
: mutex3807.c
Author
: Amar Chandole
Roll No.
: 3807
Problem Statement : Implementing a file system in a Linux OS.
====================================================
*/

#include<linux/module.h>
#include<linux/proc_fs.h>
#include<linux/seq_file.h>
static int hello_proc_show(struct seq_file *m, void *v)
{
seq_printf(m, "Hello proc ! \n");
return 0;
}
static int hello_proc_open(struct inode *inode,struct file *file)
{
printk(KERN_INFO "Module inserted now opening the proc file! \n");
return single_open(file, hello_proc_show, NULL);
}
static const struct file_operations hello_proc_fops=
{
.owner=THIS_MODULE,
.open=hello_proc_open,
.read=seq_read,
.release=single_release,
};
int init_module(void)
{
proc_create("hello_proc", 0, NULL, &hello_proc_fops);
return 0;
}
void cleanup_module(void)
{
printk(KERN_INFO "Module remove and now deleting the proc file! \n");
remove_proc_entry("hello_proc", NULL);
}
MODULE_LICENSE("GPL");/*
==============================OUTPUT=============================
amar@Amar-Dell-System-Inspiron-5420:/home/amar/Desktop/ass9$ sudo su
[sudo] password for amar:
root@Amar-Dell-System-Inspiron-5420:/home/amar/Desktop/ass9 # make
make -C /lib/modules/3.13.0-24-generic/build M=/home/it/Desktop/ass9 modules
make[1]: Entering directory `/usr/src/linux-headers-3.13.0-24-generic'
Building modules, stage 2.
MODPOST 1 modules
make[1]: Leaving directory `/usr/src/linux-headers-3.13.0-24-generic'
root@Amar-Dell-System-Inspiron-5420:/home/amar/Desktop/ass9 #insmod new-proc.ko
root@Amar-Dell-System-Inspiron-5420:/home/amar/Desktop/ass9 #cat /proc/hello_pro
c
Hello proc !
*/

Potrebbero piacerti anche