Program 1-9

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

# PROGRAM 1-Write a C program which creates a child process.

The
parent
process must wait until the child finishes. Both the processes must print
its own
pid and its parent pid.
[Use waitpid()]
CODE :
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
int pid;
int status=-1;
pid=fork();
if(pid==-1)
{
perror("fork failure");
exit(0);
}
else if(pid==0)
{
printf("In child now\n");
printf("pid of child = %d and ppid of child = %d\n",getpid(),getppid());
}
else
{
printf("In parent now\n");
waitpid(pid, &status, 0);
printf("pid of parent = %d and ppid of parent = %d\n",getpid(),getppid());
//printf("The child exited with return code %d\n", status);
exit(1);
}
}
OUTPUT :
In parent now
In child now
pid of child = 2131 and ppid of child = 2130
pid of parent = 2130 and ppid of parent = 2106
# PROGRAM 2-Write a program which calls fork() multiple times in a row,
e.g.
three times. Each forked process shall print its own PID and its parent
PID. Draw
the process tree.Determine a relation between number of times fork() is
invoked
and number of new processes created.
CODE :
#include<unistd.h>
#include<stdio.h>
int main(int argc, char *argv[])
{
int i=0;
//printf("Main Process : pid = %d and ppid = %d\n",getpid(),getppid());
fork();
printf("%d-> fork() : pid = %d and parent pid = %d\n",++i,getpid(),getppid());
fork();
printf("%d-> fork() : pid = %d and parent pid = %d\n",++i,getpid(),getppid());
fork();
printf("%d-> fork() : pid = %d and parent pid = %d\n",++i,getpid(),getppid());
}
OUTPUT :
1-> fork() : pid = 2148 and parent pid = 2106
1-> fork() : pid = 2151 and parent pid = 2148
2-> fork() : pid = 2148 and parent pid = 2106
2-> fork() : pid = 2151 and parent pid = 2148
3-> fork() : pid = 2148 and parent pid = 2106
3-> fork() : pid = 2151 and parent pid = 2148
3-> fork() : pid = 2161 and parent pid = 1
2-> fork() : pid = 2157 and parent pid = 1
[users@Magpc-6 OS]$ 3-> fork() : pid = 2157 and parent pid = 1
3-> fork() : pid = 2158 and parent pid = 1
2-> fork() : pid = 2156 and parent pid = 1
3-> fork() : pid = 2156 and parent pid = 1
3-> fork() : pid = 2162 and parent pid = 1
3-> fork() : pid = 2164 and parent pid = 1
#PROGRAM 3-Write a program which calls fork(), and make the parent
process
terminate while the child runs indefinitely. Does the child process get a
new
parent? If so, which process becomes its parent and is there anything
special
about the new process?
CODE :
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int pid = fork();
if (pid > 0)
{
printf("in parent process\n");
printf("pid of parent = %d and ppid of parent = %d\n",getpid(),getppid());
}
else if (pid == 0)
{
printf("in child process before sleep()\n");
printf("pid of child = %d and ppid of child = %d\n",getpid(),getppid());
sleep(10);
printf("in child process after sleep()\n"); //This is now an orphan process
printf("pid of child = %d and ppid of child = %d\n",getpid(),getppid()); // parent will be the init process
}
return 0;
}
OUTPUT :
in parent process
in child process before sleep()
pid of parent = 2176 and ppid of parent = 2106
pid of child = 2177 and ppid of child = 2176
[users@Magpc-6 OS]$ in child process after sleep()
pid of child = 2177 and ppid of child = 1
# PROGRAM 4-Create a program which opens a pipe. Execute ls and
redirect the
output into the pipe. Then read data from the pipe and print it. Your
program
should print a statement before writing data read from the pipe. [Use
exec()
family of functions]
CODE :
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>
void main()
{
int pf[2];
pipe(pf);
char str[1000];
char *args[]={"ls","-l",NULL};
if(fork()==0)
{
printf("Inside child:\n");
close(pf[0]);
dup2(pf[1],1);
write(pf[1],execvp(args[0],args),1000);
close(pf[1]);
}
else
{
wait(NULL);
printf("Inside Parent:\n");
close(pf[1]);
read(pf[0],str,1000);
printf("Message from child:%s\n",str);
close(pf[0]);
}
}
OUTPUT :
Inside child:
Inside Parent:
Message from child:total 76
-rwxr-xr-x. 1 users users 656 Oct 13 13:44 1.c
-rwxr-xr-x. 1 users users 915 Oct 14 08:37 2.c
-rwxr-xr-x. 1 users users 672 Oct 14 16:33 3.c
-rwxr-xr-x. 1 users users 481 Nov 9 06:22 4.c
-rwxr-xr-x. 1 users users 540 Oct 16 04:28 5_shmemReader.c
-rwxr-xr-x. 1 users users 529 Oct 16 04:28 5_shmemWriter.c
-rwxr-xr-x. 1 users users 638 Nov 12 10:22 6.c
-rwxr-xr-x. 1 users users 1458 Oct 23 16:35 7_1.c
-rwxr-xr-x. 1 users users 1843 Oct 23 04:35 7.c
-rwxr-xr-x. 1 users users 955 Oct 23 04:48 8.c
-rwxr-xr-x. 1 users users 1021 Nov 9 05:45 9.c
-rwxrwxr-x. 1 users users 5717 Nov 15 13:50 a.out
-rwxr-xr-x. 1 users users 8920 Nov 13 10:21 r
-rwxr-xr-x. 1 users users 8968 Nov 13 10:22 w
# Program 5: Create two processes A and B from two terminals. Both
process A
and B uses shared memory segment for inter process communication.
Process
A writes a number into the shared memory segment and then sleeps for
10
seconds. Process B reads a number from the shared memory segment
and then
sleeps for 10
seconds.
CODE :
Writer:
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdlib.h>
#include<unistd.h>
void main(){
key_t key = 256;
int shmid, i;
char *buffer;
if((shmid = shmget(key, 10, IPC_CREAT | 0666))==-1){
printf("Cannot create shared memory\n");
exit(0);
}
buffer = shmat(shmid, NULL, 0);
printf("Enter a number : ");
gets(buffer);
printf("\nThe key is %d\n", key);
printf("Shared memory id is %d\n", shmid);
shmdt(buffer);
sleep(10);
}
Reader:
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdlib.h>
#include<unistd.h>
void main(){
key_t key = 256;
int shmid, i;
char *buffer;
if((shmid = shmget(key, 10, IPC_CREAT | 0666))==-1){
printf("Cannot create shared memory\n");
exit(0);
}
buffer = shmat(shmid, NULL, 0);
printf("Data Read from shared memory : %s",buffer);
printf("\nThe key is %d\n", key);
printf("Shared memory id is %d\n", shmid);
shmdt(buffer);
sleep(10);
}
OUTPUT :
[user@Magpc-5 OS]$ ./w
Enter a number : 345
The key is 256
Shared memory id is 3112978
[user@Magpc-5 OS]$ gcc 5_shmemReader.c -o r
[user@Magpc-5 OS]$ ./r
Data Read from shared memory : 345
The key is 256
# PROGRAM 6 -Write a C program which finds out prime numbers
between the
range 1 to MAX by creating n child processes and subdividing the task
equally
among all child processes. Value of MAX and n are passed as command
line
arguments. The parent process must wait until all child process finishes.
CODE:
#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>
#include<math.h>
int main(int argc,char *argv[])
{
int max,n,diff,i,j,k,first,last,pid,flag,count=0;
if(argc!=3)
{
printf("Too few arguments\n");;
exit(1);
}
max=atoi(argv[1]);
n=atoi(argv[2]);
diff=max/n-1;
printf("\nPrime numbers between 1 and %d according as list: \n",max);
first=1;
last=first+diff;
for(i=1;i<=n;i++)
{
count=0;
pid=fork();
if(pid==0)
{
printf("\n%d) Child [[ %d ]] of parent [[ %d ]]: ",i,getpid(),getppid());
printf("Primes between ( %d , %d ) are: ",first, last);
for(j=first;j<=last;j++)
{
flag=0;
if(j!=1)
{
for(k=2;k<=sqrt(j);k++)
if(j%k==0)
{flag=1; break;}
if(flag==0)
{
printf("%d ",j);
count++;
}
}
}
if(count==0)
printf("This interval contains no prime numbers..\n");
printf("\n");
return 0;
}
else
wait(NULL);
//Incremental interval condition
first=last+1;last=first+diff;
if((last>max) || (i==n-1))
last=max;
if(first>max)
break;
}
printf("\n");
return 0;
}
OUTPUT :
Prime numbers between 1 and 30 according as list:
1) Child [[ 11542 ]] of parent [[ 11541 ]]: Primes between ( 1 , 10 ) are: 2 3 5 7
2) Child [[ 11543 ]] of parent [[ 11541 ]]: Primes between ( 11 , 20 ) are: 11 13 17 19
3) Child [[ 11544 ]] of parent [[ 11541 ]]: Primes between ( 21 , 30 ) are: 23 29
# PROGRAM 7.Write a C program which creates a child process and
sends a
string (provided by the user) which the child process reverses and
sends it back
to the parent. The IPC to be used is pipe. Both the processes terminates
when
the input string is “quit”.
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<sys/wait.h>
#include <unistd.h>
#include <sys/types.h>
char *strrev (char *str)
{
if (!str) {
printf ("Error: invalid string\n");
return NULL;
}
char *begin = str;
char *end = str + strlen (str) - 1;
char tmp;
while (end > begin)
{
tmp = *end;
*end-- = *begin;
*begin++ = tmp;
}
return str;
} int main(void)
{
int fd[2], nbytes;
pid_t childpid;
char string[100];
char readbuffer[80];
int status=-1;
while(strcmp(string,"quit")!=0)
{
pipe(fd);
printf("Enter a string : ");
scanf("%s", string);
if(strcmp(string,"quit")==0)
break;
else {
if((childpid = fork()) == -1)
{
printf("fork failure");
exit(1);
}
if(childpid == 0)
{
close(fd[0]);
if(strcmp(string,"quit")==0)
exit(0);
write(fd[1], strrev(string), (strlen(string)+1));
exit(0);
}
else
{
waitpid(childpid, &status, 0);
close(fd[1]);
read(fd[0], readbuffer, sizeof(readbuffer));
printf("Reversed string: %s\n", readbuffer);
}
}
}
return(0);
}
OUTPUT :
Enter a string : computer
Reversed string: retupmoc
Enter a string : madam
Reversed string: madam
Enter a string : operator
Reversed string: rotarepo
Enter a string : quit
# PROGRAM 8.Implement the solution to the producer-consumer
problem using
shared variables.
producer:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<stdbool.h>
#include <sys/ipc.h>
#include <sys/shm.h>
struct buffer
{
char buff[4][100];
int count;
};
struct share
{
bool flag[2];
int turn;
};
int main()
{
key_t key1=258,key2=259;
int shmid1,shmid2,in;
struct share *sh;
struct buffer *buf;
shmid1=shmget(key1,sizeof(struct share),IPC_CREAT|0666);
if(shmid1==-1)
{
printf("Can't create shared memory.\n");
exit(0);
}
shmid2=shmget(key2,sizeof(struct buffer),IPC_CREAT|0666);
if(shmid1==-1)
{
printf("Can't create shared memory.\n");
exit(0);
}
sh=shmat(shmid1,NULL,0);
buf=shmat(shmid2,NULL,0);
sh->flag[0]=false;
sh->flag[1]=false;
sh->turn=0;
in=0;
buf->count=0;
do
{
while(buf->count==4);
{
printf("Enter something:\n");
scanf("%s",buf->buff[in]);
in=(in+1)%4;
}
sh->flag[0]=true;sh->turn=1;
while(sh->flag[1]&&sh->turn==1);
buf->count++;
sh->flag[0]=false;
}while(1);
shmdt(buf);
shmdt(sh);
}
Output Producer:
Enter something:
hello
Enter something:
rk
Enter something:
HELLO
Enter something:
alone
Enter something:
^Z
[1]+ Stopped
consumer:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<stdbool.h>
#include <sys/ipc.h>
#include <sys/shm.h>
struct share
{
bool flag[2];
int turn;
};
struct buffer
{
char buff[4][100];
int count;
};
int main()
{
key_t key1=258,key2=259;
int shmid1,shmid2,out;
struct buffer *buf;
struct share *sh;
shmid1=shmget(key1,sizeof(struct share),IPC_CREAT|0666);
if(shmid1==-1)
{
printf("Can't create shared memory.\n");
exit(0);
}
shmid2=shmget(key2,sizeof(struct buffer),IPC_CREAT|066);
if(shmid1==-1)
{
printf("Can't create shared memory.\n");
exit(0);
}
sh=shmat(shmid1,NULL,0);
buf=shmat(shmid2,NULL,0);
sh->flag[0]=false;
sh->flag[1]=false;
sh->turn=0;
out=0;
buf->count=0;
do
{
while(buf->count==0);
printf("The string from consumer:%s\n",buf->buff[out]);
sleep(10);
out=(out+1)%4;
sh->flag[1]=true;sh->turn=0;
while(sh->flag[0]&&sh->turn==0);
buf->count--;
sh->flag[1]=false;
}while(1);
}
output consumer:
The string from consumer:hello
The string from consumer:rk
The string from consumer: HELLO
# PROGRAM 9. Write a C program which creates a child process. The
parent and
child process communicate using a shared memory segment. The
parent
process generates 100 random integers and writes it into the shared
memory
segment. The child process then computes the maximum, minimum and
average of all these 100 numbers and writes the result back into the
shared
memory segment, from where the parent process reads the result and
displays
it. Add appropriate code to synchronize the parent and child process.
[Hint: It is
an example of strict alteration where access to the shared memory
segment
alternates between the parent and child process]
CODE :
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
void main()
{
int shmid, status,key=256;
int *a, *b;
int i,max=0,min=2147483647;
long int sum=0;
float avg;
shmid = shmget(key, 10, IPC_CREAT | 0666);
if (fork() == 0) {
b = (int *) shmat(shmid, 0, 0);
printf("\nChild reads : -\n---------------\n");
for( i=0; i<100; i++)
{
if(min>b[i])
min=b[i];
if(max<b[i])
max=b[i];
sum+=b[i];
printf("%d ",b[i]);
}
printf("\n");
avg=sum/100.00;
b[101]=min;
b[102]=max;
b[103]=avg;
shmdt(b);
}
else {
a = (int *) shmat(shmid, 0, 0);
printf("\nParent Writes : -\n-----------------\n");
for(i=0;i<100;i++)
{
a[i]=rand()%9;
printf("%d ",a[i]);
}
printf("\n");
wait(&status);
min=a[101];
max=a[102];
avg=a[103];
printf("\n\nParent reads and displays------------\nMinimum : %d, Maximum : %d, Average : %.2f\
n",min,max,avg);
shmdt(a);
shmctl(shmid, IPC_RMID, 0);
}
}
OUTPUT :
Parent Writes : -
-----------------
170757136154575460718866888411500353174760025452232118
805544
6056287342000026256576685362816680117032
Child reads : -
---------------
170757136154575460718866888411500353174760025452232118
805544
6056287342000026256576685362816680117032
Parent reads and displays------------
Minimum : 0, Maximum : 8, Average : 3.00

You might also like