0% found this document useful (0 votes)
8 views

Final

Uploaded by

faizyabiqbal21
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Final

Uploaded by

faizyabiqbal21
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Question:

You are tasked to write a C program that demonstrates the use of the fork()
system call in Linux.

The program should create multiple child processes and manage them correctly.
Follow the

instructions below:

1. Program Structure:

o The parent process should create three child processes.

o Each child process should perform a unique task as described below:

 Child 1: Calculate the sum of integers from 1 to N (input provided by the

user).

 Child 2: Calculate the factorial of a given number M (input provided by the

user).

 Child 3: Print the Fibonacci series up to a number X (input provided by the

user).

2. Process Management:

o The parent process should wait for all three child processes to complete before
it

exits.

o Each child process should print its process ID (PID) and the result of its task.

o The parent process should print a message indicating it has successfully waited
for

all child processes to complete.


3. Input:

The program should prompt the user for three inputs:

o N for the sum calculation (used by Child 1),

o M for the factorial calculation (used by Child 2),

o X for the Fibonacci series (used by Child 3).

4. Error Handling:

o Ensure that the fork() system call is handled appropriately, and the program

terminates gracefully if fork() fails.

o Handle user inputs that are invalid (e.g., negative numbers).

5. Bonus (Optional):

o Implement a signal handling mechanism that catches the SIGCHLD signal in


the

parent process to detect when a child process has terminated.

Steps to Create, Compile, and Run the C++ Program on Ubuntu

1. Open the Terminal

Press Ctrl + Alt + T to open the terminal in Ubuntu.

2. Create the C++ Program File

1. Open a text editor (e.g., nano) to create your C++ program. In the terminal, type the
following command to create a new C++ file:

bash
Copy code
nano fork_example.cpp

2. Paste the following C++ code into the editor (this code demonstrates the use of fork() to
create child processes that perform different tasks):

cpp
Copy code
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

// Function to calculate the sum of integers from 1 to N


void calculate_sum(int N) {
int sum = 0;
for (int i = 1; i <= N; i++) {
sum += i;
}
printf("Child 1 (PID: %d): Sum from 1 to %d is %d\n", getpid(), N, sum);
}

// Function to calculate the factorial of M


void calculate_factorial(int M) {
long long fact = 1;
if (M < 0) {
printf("Child 2 (PID: %d): Invalid input for factorial.\n", getpid());
return;
}
for (int i = 1; i <= M; i++) {
fact *= i;
}
printf("Child 2 (PID: %d): Factorial of %d is %lld\n", getpid(), M, fact);
}

// Function to print Fibonacci series up to X


void print_fibonacci(int X) {
int a = 0, b = 1, next;
if (X <= 0) {
printf("Child 3 (PID: %d): Invalid input for Fibonacci series.\n",
getpid());
return;
}
printf("Child 3 (PID: %d): Fibonacci series up to %d: ", getpid(), X);
while (a <= X) {
printf("%d ", a);
next = a + b;
a = b;
b = next;
}
printf("\n");
}

int main() {
int N, M, X;
// Prompt user for inputs
printf("Enter a number N for sum calculation: ");
scanf("%d", &N);

printf("Enter a number M for factorial calculation: ");


scanf("%d", &M);

printf("Enter a number X for Fibonacci series: ");


scanf("%d", &X);

// Error handling for negative values


if (N < 1 || M < 0 || X < 0) {
printf("Error: Invalid input. N must be positive, M and X must be non-
negative.\n");
exit(1);
}

pid_t pid1, pid2, pid3;

// Create the first child (Child 1: Sum calculation)


pid1 = fork();
if (pid1 < 0) {
perror("fork failed for Child 1");
exit(1);
} else if (pid1 == 0) {
calculate_sum(N);
exit(0);
}

// Create the second child (Child 2: Factorial calculation)


pid2 = fork();
if (pid2 < 0) {
perror("fork failed for Child 2");
exit(1);
} else if (pid2 == 0) {
calculate_factorial(M);
exit(0);
}

// Create the third child (Child 3: Fibonacci series)


pid3 = fork();
if (pid3 < 0) {
perror("fork failed for Child 3");
exit(1);
} else if (pid3 == 0) {
print_fibonacci(X);
exit(0);
}

// Parent process waits for all child processes


int status;
waitpid(pid1, &status, 0);
waitpid(pid2, &status, 0);
waitpid(pid3, &status, 0);

// Indicating the parent has waited for all children


printf("Parent (PID: %d): All child processes have completed.\n",
getpid());

return 0;
}

3. After pasting the code, press Ctrl + O to save the file, then press Enter to confirm.
Finally, press Ctrl + X to exit the nano editor.

3. Compile the C++ Program

Now, you need to compile the C++ program using G++ (the GNU C++ compiler).

1. In the terminal, run the following command to compile the program:

bash
Copy code
g++ fork_example.cpp -o fork_example

o fork_example.cpp is the source code file.


o -o fork_example specifies the name of the compiled output file (in this case,
fork_example).
2. If there are no errors, the program will be compiled successfully, and you will see no
output. The compiled file will be created as fork_example.

4. Run the Compiled Program

Now that the program is compiled, you can run it:

1. In the terminal, run the program by executing:

bash
Copy code
./fork_example

2. The program will prompt you for input. For example:

mathematica
Copy code
Enter a number N for sum calculation: 5
Enter a number M for factorial calculation: 4
Enter a number X for Fibonacci series: 10

3. The program will create three child processes, and each will perform the respective tasks.
You will see output similar to this:

less
Copy code
Child 1 (PID: 12345): Sum from 1 to 5 is 15
Child 2 (PID: 12346): Factorial of 4 is 24
Child 3 (PID: 12347): Fibonacci series up to 10: 0 1 1 2 3 5 8
Parent (PID: 12344): All child processes have completed.

Error Handling

 The program includes basic error handling to check for invalid inputs (like negative
numbers for the factorial and Fibonacci series).
 If fork() fails, the program will output an error message and terminate gracefully.

General Steps to Create, Compile, and Run C++ Programs in Ubuntu

1. Open the Terminal in Ubuntu by pressing Ctrl + Alt + T.


2. Create a C++ Program File using a text editor such as nano.

1. Display the Welcome Screen

Create a simple C++ program to display a welcome message.

cpp
Copy code
// welcome.cpp
#include <iostream>
using namespace std;

int main() {
cout << "Welcome to the C++ Program!" << endl;
return 0;
}

 Save the file: Press Ctrl + O, then Enter, then Ctrl + X to exit.
 Compile: g++ welcome.cpp -o welcome
 Run: ./welcome

2. Display Five Values Entered by User


This program will ask the user to input five values and then display them.

cpp
Copy code
// five_values.cpp
#include <iostream>
using namespace std;

int main() {
int values[5];
cout << "Enter 5 values:" << endl;
for (int i = 0; i < 5; i++) {
cin >> values[i];
}

cout << "You entered: ";


for (int i = 0; i < 5; i++) {
cout << values[i] << " ";
}
cout << endl;

return 0;
}

 Compile: g++ five_values.cpp -o five_values


 Run: ./five_values

3. Swap Two Floating Points and Display the Result

This program swaps two floating-point numbers entered by the user.

cpp
Copy code
// swap_floats.cpp
#include <iostream>
using namespace std;

int main() {
float a, b;
cout << "Enter two floating-point numbers: ";
cin >> a >> b;

cout << "Before swap: a = " << a << ", b = " << b << endl;

// Swapping
float temp = a;
a = b;
b = temp;

cout << "After swap: a = " << a << ", b = " << b << endl;

return 0;
}

 Compile: g++ swap_floats.cpp -o swap_floats


 Run: ./swap_floats

4. Display the Area of a Circle

This program calculates the area of a circle given the radius.

cpp
Copy code
// area_of_circle.cpp
#include <iostream>
#include <cmath>
using namespace std;

int main() {
float radius;
cout << "Enter the radius of the circle: ";
cin >> radius;

float area = M_PI * radius * radius;


cout << "The area of the circle is: " << area << endl;

return 0;
}

 Compile: g++ area_of_circle.cpp -o area_of_circle -lm (Use -lm to link the


math library)
 Run: ./area_of_circle

5. Display the Circumference of a Circle

This program calculates the circumference of a circle.

cpp
Copy code
// circumference_of_circle.cpp
#include <iostream>
#include <cmath>
using namespace std;

int main() {
float radius;
cout << "Enter the radius of the circle: ";
cin >> radius;
float circumference = 2 * M_PI * radius;
cout << "The circumference of the circle is: " << circumference << endl;

return 0;
}

 Compile: g++ circumference_of_circle.cpp -o circumference_of_circle -lm


 Run: ./circumference_of_circle

6. Display the Area of a Sector

This program calculates the area of a sector based on the radius and angle.

cpp
Copy code
// area_of_sector.cpp
#include <iostream>
#include <cmath>
using namespace std;

int main() {
float radius, angle;
cout << "Enter the radius of the circle: ";
cin >> radius;
cout << "Enter the angle of the sector in degrees: ";
cin >> angle;

float area = (M_PI * radius * radius * angle) / 360;


cout << "The area of the sector is: " << area << endl;

return 0;
}

 Compile: g++ area_of_sector.cpp -o area_of_sector -lm


 Run: ./area_of_sector

7. Display the Table of a Customized Input Value

This program displays the multiplication table for a number entered by the user.

cpp
Copy code
// multiplication_table.cpp
#include <iostream>
using namespace std;

int main() {
int num;
cout << "Enter a number to display its multiplication table: ";
cin >> num;

for (int i = 1; i <= 10; i++) {


cout << num << " * " << i << " = " << num * i << endl;
}

return 0;
}

 Compile: g++ multiplication_table.cpp -o multiplication_table


 Run: ./multiplication_table

8. Display the User Name, Age, and Address

This program collects the user's name, age, and address and displays it.

cpp
Copy code
// user_info.cpp
#include <iostream>
#include <string>
using namespace std;

int main() {
string name, address;
int age;

cout << "Enter your name: ";


getline(cin, name);

cout << "Enter your age: ";


cin >> age;

cin.ignore(); // to clear the input buffer before reading the address


cout << "Enter your address: ";
getline(cin, address);

cout << "Name: " << name << endl;


cout << "Age: " << age << endl;
cout << "Address: " << address << endl;

return 0;
}

 Compile: g++ user_info.cpp -o user_info


 Run: ./user_info
9. Display the Greater of Three Input Values

This program finds the greatest of three values entered by the user.

cpp
Copy code
// greatest_of_three.cpp
#include <iostream>
using namespace std;

int main() {
int a, b, c;
cout << "Enter three numbers: ";
cin >> a >> b >> c;

int greatest = a;
if (b > greatest) greatest = b;
if (c > greatest) greatest = c;

cout << "The greatest number is: " << greatest << endl;

return 0;
}

 Compile: g++ greatest_of_three.cpp -o greatest_of_three


 Run: ./greatest_of_three

10. Display the Maximum and Minimum Value from the Input

This program calculates the maximum and minimum values from three numbers.

cpp
Copy code
// max_min_values.cpp
#include <iostream>
using namespace std;

int main() {
int a, b, c;
cout << "Enter three numbers: ";
cin >> a >> b >> c;

int maximum = a;
int minimum = a;

if (b > maximum) maximum = b;


if (c > maximum) maximum = c;

if (b < minimum) minimum = b;


if (c < minimum) minimum = c;
cout << "The maximum value is: " << maximum << endl;
cout << "The minimum value is: " << minimum << endl;

return 0;
}

 Compile: g++ max_min_values.cpp -o max_min_values


 Run: ./max_min_values

1. User Configuration Files in Linux

Description:

Linux uses configuration files to manage user accounts, their default settings, and permissions.
Important user-related configuration files include:

 /etc/passwd: Stores user account details.


 /etc/shadow: Stores encrypted passwords and password aging information.
 /etc/group: Defines groups and their members.
 /etc/skel: Provides default files for new user home directories.

Commands:

1. View the user account details:


bash
Copy code
cat /etc/passwd

2. View encrypted passwords:

bash
Copy code
sudo cat /etc/shadow

3. List default files copied to new users’ home directories:

bash
Copy code
ls -la /etc/skel

2. Managing User Environment

Description:

Each user has a customizable environment stored in hidden configuration files in their home
directory, such as .bashrc, .profile, and .bash_profile.

Commands:

1. Edit .bashrc for a specific user:

bash
Copy code
nano ~/.bashrc

Add a welcome message:

bash
Copy code
echo "Welcome, $USER!" >> ~/.bashrc

2. Apply changes:

bash
Copy code
source ~/.bashrc

3. Set environment variables:

bash
Copy code
export PATH=$PATH:/new/path
3. Adding and Removing Users

Description:

The system administrator can add, modify, and delete users using various commands.

Commands:

1. Add a new user:

bash
Copy code
sudo adduser irfan

o Follow the prompts to set a password and user details.


2. Modify user information:

bash
Copy code
sudo usermod -c "Irfan Karim, Administrator" irfan

3. Delete a user:

bash
Copy code
sudo deluser irfan

o To delete the user's home directory:

bash
Copy code
sudo deluser --remove-home irfan

4. Change user password:

bash
Copy code
sudo passwd irfan

4. Lightweight Directory Access Protocol (LDAP)

Description:

LDAP is used to centralize authentication and user account management in large environments.

Commands:

1. Install LDAP client:


bash
Copy code
sudo apt update
sudo apt install ldap-utils

2. Query LDAP server:

bash
Copy code
ldapsearch -x -LLL -H ldap://ldap.example.com -b "dc=example,dc=com"

5. Pluggable Authentication Modules (PAM)

Description:

PAM provides a framework for authentication-related modules to be plugged into a Linux


system.

Commands:

1. View PAM configuration:

bash
Copy code
ls /etc/pam.d/

2. Enable password complexity: Edit the PAM file for password quality:

bash
Copy code
sudo nano /etc/pam.d/common-password

Add:

bash
Copy code
password requisite pam_pwquality.so retry=3 minlen=8

C++ Example: Displaying User Details

To demonstrate a program that interacts with the Linux system, you can create a C++ program to
display user details.

cpp
Copy code
#include <iostream>
#include <cstdlib>
int main() {
// Execute the "whoami" command to get the current user
std::cout << "Current user: ";
system("whoami");

// Execute the "id" command to get user ID details


std::cout << "User details: ";
system("id");

// Execute the "pwd" command to display current working directory


std::cout << "Current directory: ";
system("pwd");

return 0;
}

Steps to Compile and Run:

1. Save the file as user_info.cpp.


2. Compile:

bash
Copy code
g++ user_info.cpp -o user_info

3. Run:

bash
Copy code
./user_info

File and Directory Navigation

1. Find Your Current Directory


Command:

bash
Copy code
pwd
Output: Prints the present working directory.

2. List All Files in Your Home Directory (Including Hidden Files)


Command:

bash
Copy code
ls -la ~

Output: Lists all files, including hidden files (those starting with .).

3. Change to the /tmp Directory


Command:

bash
Copy code
cd /tmp

Output: Changes the directory to /tmp.

4. Create a New Directory Called linux_practice in Your Home Directory


Command:

bash
Copy code
mkdir ~/linux_practice

Output: Creates the linux_practice directory in the home directory.

5. Move to the linux_practice Directory


Command:

bash
Copy code
cd ~/linux_practice

Output: Changes the directory to linux_practice.

6. Create a New Empty File Called example.txt


Command:

bash
Copy code
touch example.txt

Output: Creates an empty file named example.txt.

7. Copy example.txt to backup.txt


Command:
bash
Copy code
cp example.txt backup.txt

Output: Creates a copy named backup.txt.

8. Rename backup.txt to archive.txt


Command:

bash
Copy code
mv backup.txt archive.txt

Output: Renames backup.txt to archive.txt.

9. Delete example.txt
Command:

bash
Copy code
rm example.txt

Output: Deletes the file example.txt.

10. Move Back to Your Home Directory


Command:

bash
Copy code
cd ~

Output: Changes the directory back to the home directory.

File Viewing

1. Create a Text File Called notes.txt with the Following Content


Content:

csharp
Copy code
Linux is a powerful operating system.
The terminal gives you direct control.

Command:

bash
Copy code
echo -e "Linux is a powerful operating system.\nThe terminal gives you
direct control." > notes.txt

Output: Creates notes.txt with the specified content.

2. Display the Content of notes.txt Using cat


Command:

bash
Copy code
cat notes.txt

Output: Displays the entire content of notes.txt.

3. Display the Content of notes.txt Using less


Command:

bash
Copy code
less notes.txt

Output: Opens the content in a scrollable view (press q to exit).

4. Display the First Two Lines of notes.txt Using head


Command:

bash
Copy code
head -n 2 notes.txt

Output: Displays the first two lines of notes.txt.

5. Display the Last Two Lines of notes.txt Using tail


Command:

bash
Copy code
tail -n 2 notes.txt

Output: Displays the last two lines of notes.txt.

Steps for Execution and Verification

To execute these commands:

1. Open the terminal on Ubuntu.


2. Type each command step by step, following the sequence provided.
3. Verify the results after executing each command.

Sample C++ Code for File Handling

To integrate file handling in C++ and simulate viewing a file, here is an example program:

cpp
Copy code
#include <iostream>
#include <fstream>
#include <string>

int main() {
std::ofstream outfile("notes.txt");
outfile << "Linux is a powerful operating system.\n";
outfile << "The terminal gives you direct control.\n";
outfile.close();

std::ifstream infile("notes.txt");
std::string line;

std::cout << "Content of notes.txt:\n";


while (std::getline(infile, line)) {
std::cout << line << std::endl;
}
infile.close();

return 0;
}

Steps to Compile and Run the C++ Code:

1. Save the file as file_viewing.cpp.


2. Compile:

bash
Copy code
g++ file_viewing.cpp -o file_viewing

3. Run:

bash
Copy code
./file_viewing

This will display the content of notes.txt in the terminal. Let me know if you'd like assistance
with any specific task!
Step-by-Step Guide to Install Ubuntu

This guide will help you install Ubuntu, a popular Linux operating system, on your computer.
Follow the steps below to successfully complete the installation.

Prerequisites

1. System Requirements:
o 2 GHz dual-core processor or better.
o 4 GB of RAM or more.
o At least 25 GB of free storage space.
2. Bootable Media:
o A USB flash drive with at least 8 GB capacity or a DVD.
o Ubuntu ISO file (download from the official Ubuntu website).
3. Backup Your Data:
o Back up your important files, as installing Ubuntu may erase your existing
operating system and data.
4. BIOS/UEFI Access:
o Familiarize yourself with accessing BIOS/UEFI to modify boot order.

Step 1: Download Ubuntu ISO

1. Visit Ubuntu Downloads.


2. Select the desired version (e.g., Ubuntu Desktop 22.04 LTS).
3. Download the ISO file.

Step 2: Create a Bootable USB/DVD

1. Using Rufus (Windows):


o Download and install Rufus.
o Insert your USB drive.
o Open Rufus, select the downloaded ISO, and create a bootable USB.
2. Using Etcher (Windows/Mac/Linux):
o Download and install Etcher.
o Select the ISO file and the USB drive, then click "Flash."
3. Burn ISO to DVD (Optional):
o Use any disk burning software like Brasero or Windows DVD burner.

Step 3: Boot from the USB/DVD

1. Restart your computer.


2. Access the BIOS/UEFI settings by pressing a key during boot (e.g., F2, F10, DEL, or ESC,
depending on your system).
3. Set the boot order to prioritize the USB/DVD drive.
4. Save and exit BIOS/UEFI.

Step 4: Start the Installation Process

1. Insert the bootable USB/DVD and restart your computer.


2. Select "Try or Install Ubuntu" from the boot menu.
3. You’ll see two options:
o Try Ubuntu: Use Ubuntu without installing.
o Install Ubuntu: Begin the installation process.

Step 5: Configure Installation Settings

1. Keyboard Layout:
o Select your preferred keyboard layout and click "Continue."
2. Updates and Software:
o Choose whether to install updates and third-party software for graphics, Wi-Fi,
and additional media formats.
3. Installation Type:
o Erase Disk and Install Ubuntu: This will remove all existing data and operating
systems.
o Dual Boot (Install Alongside Existing OS): Install Ubuntu alongside Windows
or another OS.
o Custom Partitioning: Advanced users can create custom partitions.
4. Partition Configuration (If Needed):
o Recommended partitions:
 / (root): At least 20 GB.
 swap: Equal to your RAM size (optional for SSDs).
 /home: For personal files.
5. User Information:
o Set your name, computer name, username, and password.

Step 6: Complete Installation

1. Review your selections and click "Install Now."


2. Follow on-screen instructions to complete the installation.
3. Once the installation finishes, remove the USB/DVD and reboot your system.

Step 7: Post-Installation Tasks

1. Update Ubuntu: Open the terminal and run:

bash
Copy code
sudo apt update && sudo apt upgrade

2. Install Additional Drivers: Open "Software & Updates," go to the "Additional Drivers"
tab, and install any proprietary drivers if needed.
3. Install Common Software:

bash
Copy code
sudo apt install build-essential git curl vim

4. Explore Ubuntu: Familiarize yourself with the desktop environment and available
applications.

You might also like