OSSP LAB ASSIGNMENT-2
VIDU, 9918103087 F3
Q1)
ZOMBIE PROCESS
Q3)
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main ()
{
int pid_t ,child_pid;
child_pid = fork ();
if (child_pid > 0) {
sleep (60);
}
else {
exit (0);
}
return 0;
}
Q4)
For every process hello runs 2 times. Therefore for three forks. We have 2^3 that is 8
hellos
#include <stdio.h>
#include <unistd.h>
// Driver code
int main()
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sumOdd = 0, sumEven = 0, n, i;
n = fork();
// Checking if n is not 0
if (n > 0) {
for (i = 0; i < 10; i++) {
if (a[i] % 2 == 0)
sumEven = sumEven + a[i];
printf("Parent process \n";
cout << "Sum of even no. is " << sumEven << endl; }
// If n is 0 i.e. we are in child process
else {
for (i = 0; i < 10; i++) {
if (a[i] % 2 != 0)
sumOdd = sumOdd + a[i];
cout << "Child process \n";
cout << "\nSum of odd no. is " << sumOdd << endl; }
return 0;
}
Similarly, we can make for other.
Q6) #include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
#include<sys/wait.h>
int main()
// We use two pipes
// First pipe to send input string from parent // Second pipe to send concatenated string
from child
int fd1[2]; // Used to store two ends of first pipe int fd2[2]; // Used to store two ends of
second pipe
char fixed_str[] = "MY FUNC";
char input_str[100];
pid_t p;
if (pipe(fd1)==-1)
fprintf(stderr, "Pipe Failed" );
return 1;
if (pipe(fd2)==-1)
fprintf(stderr, "Pipe Failed" );
return 1;
}
scanf("%s", input_str);
p = fork();
if (p < 0)
fprintf(stderr, "fork Failed" );
return 1;
// Parent process
else if (p > 0)
char concat_str[100];
close(fd1[0]); // Close reading end of first pipe
// Write input string and close writing end of first // pipe.
write(fd1[1], input_str, strlen(input_str)+1); close(fd1[1]);
// Wait for child to send a string
wait(NULL);
close(fd2[1]); // Close writing end of second pipe
// Read string from child, print it and close // reading end.
read(fd2[0], concat_str, 100);
printf("Concatenated string %s\n", concat_str); close(fd2[0]);
// child process
else
close(fd1[1]); // Close writing end of first pipe
// Read a string using first pipe
char concat_str[100];
read(fd1[0], concat_str, 100);
// Concatenate a fixed string with it
int k = strlen(concat_str);
int i;
for (i=0; i<strlen(fixed_str); i++)
concat_str[k++] = fixed_str[i];
concat_str[k] = '\0'; // string ends with '\0'
// Close both reading ends
close(fd1[0]);
close(fd2[0]);
// Write concatenated string and close writing end write(fd2[1], concat_str,
strlen(concat_str)+1); close(fd2[1]);
exit(0);