0% found this document useful (0 votes)
7 views6 pages

Linux Memory and File Management Programs

Os lab note 2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views6 pages

Linux Memory and File Management Programs

Os lab note 2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

OS PRATICALS

Ass-3 Write a program to report behavior of Linux kernel including information on configured
memory, amount of free and used memory. (memory information)
Ans:
Here’s a C program that reports the behavior of the Linux kernel, including information on
configured memory, amount of free and used memory. This program reads the
/proc/meminfo file and extracts the necessary memory details.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void report_memory_behavior() {
FILE *file = fopen("/proc/meminfo", "r");
if (file == NULL) {
perror("Could not open /proc/meminfo");
return;
}

char line[256];
unsigned long total_memory = 0;
unsigned long free_memory = 0;
unsigned long available_memory = 0;

while (fgets(line, sizeof(line), file)) {


if (sscanf(line, "MemTotal: %lu kB", &total_memory) == 1) {
continue;
}
if (sscanf(line, "MemFree: %lu kB", &free_memory) == 1) {
continue;
}
if (sscanf(line, "MemAvailable: %lu kB", &available_memory) == 1) {
continue;
}
}

fclose(file);

unsigned long used_memory = total_memory - free_memory;

printf("Total Configured Memory: %lu MB\n", total_memory / 1024);


printf("Free Memory: %lu MB\n", free_memory / 1024);
printf("Used Memory: %lu MB\n", used_memory / 1024);
printf("Available Memory: %lu MB\n", available_memory / 1024);
}

int main() {
report_memory_behavior();
return 0;
}

Explanation:

1. File Opening: The program opens the /proc/meminfo file to read memory statistics.
2. Memory Variables: Variables like total_memory, free_memory, and
available_memory are defined to store values read from the file.
3. Reading and Parsing: The fgets function is used to read the file line by line. Using
sscanf, the program extracts memory information for MemTotal, MemFree, and
MemAvailable.
4. Memory Calculation: The used memory is calculated as the difference between total and
free memory.
5. Output: The memory values are printed in MB, as they are initially reported in kB in
/proc/meminfo.

Output Example:
Total Configured Memory: 8192 MB
Free Memory: 2048 MB
Used Memory: 6144 MB
Available Memory: 3072 MB

Notes:

 This program is designed to run on Linux systems that have the /proc/meminfo file.
 It assumes the system reports memory in kilobytes (kB) as is typical in /proc/meminfo.
The program converts these values to megabytes (MB) for readability.

Ass-4 Write a program to print file details including owner access permissions, file access
time, where file name is given as argument.
Ans:
Here’s a C program that prints file details, including the owner’s access permissions and the last
file access time. The program accepts a file name as an argument and uses system calls like
stat to get the file information.
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
#include <unistd.h>

// Function to print file permissions in a readable format


void print_permissions(mode_t mode) {
printf( (S_ISDIR(mode)) ? "d" : "-");
printf( (mode & S_IRUSR) ? "r" : "-");
printf( (mode & S_IWUSR) ? "w" : "-");
printf( (mode & S_IXUSR) ? "x" : "-");
printf( (mode & S_IRGRP) ? "r" : "-");
printf( (mode & S_IWGRP) ? "w" : "-");
printf( (mode & S_IXGRP) ? "x" : "-");
printf( (mode & S_IROTH) ? "r" : "-");
printf( (mode & S_IWOTH) ? "w" : "-");
printf( (mode & S_IXOTH) ? "x" : "-");
printf("\n");
}

int main(int argc, char *argv[]) {


if (argc != 2) {
fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
return EXIT_FAILURE;
}

const char *filename = argv[1];


struct stat file_stat;

// Get file statistics


if (stat(filename, &file_stat) == -1) {
perror("stat");
return EXIT_FAILURE;
}

// Print file permissions


printf("File Permissions: ");
print_permissions(file_stat.st_mode);

// Print file owner's username and group name


struct passwd *pw = getpwuid(file_stat.st_uid);
struct group *gr = getgrgid(file_stat.st_gid);

printf("Owner: %s\n", pw ? pw->pw_name : "Unknown");


printf("Group: %s\n", gr ? gr->gr_name : "Unknown");
// Print last access time
printf("Last Access Time: %s", ctime(&file_stat.st_atime));

return EXIT_SUCCESS;
}

Explanation:

1. stat() System Call: The program uses stat() to obtain file information such as
permissions, owner, and access times.
2. Permissions: The print_permissions() function decodes the file mode (permissions)
from the stat structure and prints it in a human-readable format.
3. Owner and Group: The program uses getpwuid() and getgrgid() to obtain the
username and group name corresponding to the file's user ID (st_uid) and group ID
(st_gid).
4. Last Access Time: The program uses ctime() to convert the last access time
(st_atime) into a human-readable string.

How to Compile and Run:

1. Save the program to a file, e.g., file_info.c.


2. Compile the program using gcc:

gcc -o file_info file_info.c


Run the program and provide a file name as an argument:
./file_info [Link]
Example Output:
File Permissions: -rw-r--r--
Owner: john
Group: staff
Last Access Time: Fri Sep 13 14:25:46 2024

 File Permissions: Displays the file permissions in a style similar to ls -l.


 Owner: The user who owns the file.
 Group: The group that owns the file.
 Last Access Time: The last time the file was accessed.

Ass-5 Write a program to copy files using system calls.


Ans:

Here’s a C program that copies files using system calls like open(), read(), write(), and
close().

Program:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

#define BUFFER_SIZE 1024

void copy_file(const char *source, const char *destination) {


int src_fd, dest_fd;
char buffer[BUFFER_SIZE];
ssize_t bytes_read, bytes_written;

// Open the source file for reading


src_fd = open(source, O_RDONLY);
if (src_fd == -1) {
perror("Error opening source file");
exit(EXIT_FAILURE);
}

// Open/Create the destination file with write permissions


dest_fd = open(destination, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (dest_fd == -1) {
perror("Error opening/creating destination file");
close(src_fd);
exit(EXIT_FAILURE);
}

// Copy content from source file to destination file


while ((bytes_read = read(src_fd, buffer, BUFFER_SIZE)) > 0) {
bytes_written = write(dest_fd, buffer, bytes_read);
if (bytes_written != bytes_read) {
perror("Error writing to destination file");
close(src_fd);
close(dest_fd);
exit(EXIT_FAILURE);
}
}

if (bytes_read == -1) {
perror("Error reading source file");
}

// Close the file descriptors


close(src_fd);
close(dest_fd);
}

int main(int argc, char *argv[]) {


if (argc != 3) {
fprintf(stderr, "Usage: %s <source file> <destination file>\n", argv[0]);
exit(EXIT_FAILURE);
}

copy_file(argv[1], argv[2]);

printf("File copied from %s to %s successfully.\n", argv[1], argv[2]);

return EXIT_SUCCESS;
}

Explanation:

1. System Calls Used:


o open(): Opens a file descriptor for both the source and destination files.
O_RDONLY is used for reading the source file, and O_WRONLY | O_CREAT |
O_TRUNC is used to create the destination file or truncate it if it already exists.
o read(): Reads from the source file into a buffer.
o write(): Writes the content from the buffer into the destination file.
o close(): Closes the file descriptors for both source and destination files.
2. Buffer: A buffer of size 1024 bytes is used to read and write in chunks, making the
program efficient for larger files.
3. File Permissions: When creating the destination file, the permissions are set to 0644
(readable and writable by the owner, and readable by others).

How to Compile and Run:

1. Save the program to a file, e.g., copy_file.c.


2. Compile the program using gcc:

gcc -o copy_file copy_file.c


Run the program by providing the source file and destination file as arguments:
./copy_file [Link] [Link]
Example:
./copy_file [Link] [Link]
Output:
File copied from [Link] to [Link] successfully.
The program will copy the content of [Link] to [Link]. If [Link] doesn't
exist, it will be created. If it exists, its contents will be overwritten.

Common questions

Powered by AI

The C program opens the /proc/meminfo file to read memory statistics such as total memory, free memory, and available memory. It uses the fgets function to read the file line by line and sscanf to extract specific memory information. The used memory is calculated by subtracting free memory from total memory. All values are displayed in megabytes for clarity .

Using stat() may not account for certain file system intricacies, such as network file systems or systems with special access restrictions that might report data differently. Additionally, files with extended attributes or ACLs might not have all aspects reflected through basic stat calls, possibly requiring additional APIs to capture comprehensive metadata .

The program retrieves the 'Last Access Time' using the st_atime attribute from the stat structure. It converts this information into a human-readable string using ctime(), ensuring compliance with conventional date and time formats. This method provides both accurate and standardized output, assuming the system clock and file metadata are up-to-date .

The program decodes and prints file permissions using bitwise operations on the mode_t variable. The print_permissions function checks specific bits to determine the type (directory or file) and the read, write, and execute permissions for the user, group, and others. The result is printed in a format similar to 'ls -l', showing a string like '-rw-r--r--' to represent the permissions .

The program utilizes the open() system call to manage file descriptors for both the source and destination files. It checks if the open() function returns -1, which indicates an error. If an error is detected during file opening, reading, or writing, perror() is called to print an error message, and exit() terminates the program safely to avoid any potential data corruption or loss .

The program calculates the memory size in megabytes by dividing the values it retrieves (which are in kilobytes) by 1024. This conversion factor (1024) accurately translates kilobytes to megabytes, essential for displaying user-friendly and readable output .

Challenges include potential changes in the format of /proc/meminfo across different Linux distributions or kernel versions, which could affect parsing. The program mitigates these issues by specifically targeting known labels (MemTotal, MemFree, MemAvailable) with sscanf. This targeted parsing assumes consistent labels but could require updates if the underlying file structure changes .

The stat() system call is used to get detailed information about a file, such as permissions, owner, and last access time. The program uses it to populate a stat structure with metadata, which is then used to print file permissions in a human-readable format using a helper function. It also retrieves the file owner's username and group name with the getpwuid() and getgrgid() functions .

Using a buffer in the file copying process significantly improves performance by minimizing the number of system calls. Instead of frequently calling read() and write() for each byte, the program processes chunks of data (1024 bytes at a time), reducing the overhead associated with switching between user and kernel mode. This makes the operation faster and more efficient, especially with larger files .

Using system calls like open(), read(), write(), and close() is efficient for file copying because they allow low-level access to file operations. This enables precise control over the file descriptors, optimizing read and write operations through a buffer method. The program specifically reads and writes in 1024-byte chunks, balancing the overhead of frequent system calls and the need for memory management .

You might also like