MCS Advanced Operating System Practical Program
MCS:
Advanced Operating System Practical Program
SLIP 1:
/*
Take multiple files as Command Line Arguments and
print their inode numbers and file types
Program Name : Slip1A.c
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
// Check if a filename is provided
if (argc < 2) {
printf("Ohhh Sorry You are not proving arguments..");
return 1;
}
char *file_path = argv[1];
struct stat file_stat;
// Get file information
if (stat(file_path, &file_stat) == 0)
{
ino_t inode_number = file_stat.st_ino;
// Print the inode number
printf("Inode number of %s: %d\n", file_path, inode_number);
// Determine file type
if (S_ISREG(file_stat.st_mode))
{
printf("%s is a regular file.\n", file_path);
}
else if (S_ISDIR(file_stat.st_mode))
{
printf("%s is a directory.\n", file_path);
}
else
{
printf("%s is of unknown type.\n", file_path);
}
}
else {
// Print an error message if stat fails
perror(file_path);
return 1;
}
return 0;
}
/* OUTPUT:
PS C:\Bootstrap Program> gcc Slip1A.c -o Slip1A
PS C:\Bootstrap Program> ./Slip1A Slip1A.c
Inode number of Slip1A.c: 0
Slip1A.c is a regular file.
*/
/*
Write a C program to send SIGALRM signal by child process to parent process and parent process
make a provision to catch the signal and display alarm is fired.(Use Kill, fork, signal and sleep
system call)
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
// Signal handler function
void alarm_handler(int signum) {
if (signum == SIGALRM) {
printf("Alarm is fired!\n");
}
}
int main() {
pid_t child_pid;
// Set up signal handler
signal(SIGALRM, alarm_handler);
// Create a child process
if ((child_pid = fork()) == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (child_pid == 0) {
// Child process
// Sleep for 2 seconds and then send SIGALRM to parent
sleep(2);
kill(getppid(), SIGALRM);
} else {
// Parent process
printf("Waiting for the alarm...\n");
// Sleep indefinitely to allow time for the child to send the signal
while (1) {
sleep(1);
}
}
return 0;
}
SLIP 2:
/*
Write a C program to find file properties such as inode number, number of hard link, File
permissions, File size, File access and modification time and so on of a given file using stat()
system call
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
int main(int argc, char *argv[]) {
// Check if a filename is provided
if (argc < 2) {
printf("Ohhh Sorry You are not proving arguments..");
return 1;
}
const char *file_path = argv[1];
struct stat file_stat;
// Get file information
if (stat(file_path, &file_stat) == 0) {
// Print file properties
printf("File Properties for: %s\n", file_path);
printf("Inode Number: %d\n", file_stat.st_ino);
printf("Number of Hard Links: %d\n", file_stat.st_nlink);
printf("File Permissions: %d\n", file_stat.st_mode & 0777); // File permission bits
printf("File Size: %d bytes\n", file_stat.st_size);
printf("Last Access Time: %s", ctime(&file_stat.st_atime));
printf("Last Modification Time: %s", ctime(&file_stat.st_mtime));
} else {
// Print an error message if stat fails
perror(file_path);
}
return 0;
}
/*
PS C:\Bootstrap Program> gcc Slip2A.c -o Slip2A
PS C:\Bootstrap Program> ./Slip2A Slip2A.c
File Properties for: Slip2A.c
Inode Number: 0
Number of Hard Links: 1
File Permissions: 438
File Size: 1300 bytes
Last Access Time: Sun Dec 10 15:11:04 2023
Last Modification Time: Sun Dec 10 15:11:04 2023
*/
/*
Write a C program that catches the ctrl-c (SIGINT) signal for the first time and display the
appropriate message and exits on pressing ctrl-c again
*/
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
// Global variable to track whether SIGINT has been received
int sigint_received = 0;
// Signal handler function for SIGINT
void sigint_handler(int signum) {
if (signum == SIGINT) {
if (!sigint_received) {
printf("Ctrl+C (SIGINT) received. Press again to exit.\n");
sigint_received = 1;
} else {
printf("Ctrl+C (SIGINT) received again. Exiting...\n");
exit(EXIT_SUCCESS);
}
}
}
int main() {
// Set up signal handler for SIGINT
signal(SIGINT, sigint_handler);
// Loop indefinitely
while (1) {
// Do some work or sleep here
}
return 0;
}
SLIP 3:
/*
Print the type of file and inode number where file name accepted through Command Line
*/
/*
Take multiple files as Command Line Arguments and
print their inode numbers and file types
Program Name : Slip1A.c
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
// Check if a filename is provided
if (argc < 2) {
printf("Ohhh Sorry You are not proving arguments..");
return 1;
}
char *file_path = argv[1];
struct stat file_stat;
// Get file information
if (stat(file_path, &file_stat) == 0)
{
ino_t inode_number = file_stat.st_ino;
// Print the inode number
printf("Inode number of %s: %d\n", file_path, inode_number);
// Determine file type
if (S_ISREG(file_stat.st_mode))
{
printf("%s is a regular file.\n", file_path);
}
else if (S_ISDIR(file_stat.st_mode))
{
printf("%s is a directory.\n", file_path);
}
else
{
printf("%s is of unknown type.\n", file_path);
}
}
else {
// Print an error message if stat fails
perror(file_path);
return 1;
}
return 0;
}
/* OUTPUT:
PS C:\Bootstrap Program> gcc Slip1A.c -o Slip1A
PS C:\Bootstrap Program> ./Slip1A Slip1A.c
Inode number of Slip1A.c: 0
Slip1A.c is a regular file.
*/
/*
Write a C program which creates a child process to run linux/ unix command or any user defined
program. The parent process set the signal handler for death of child signal and Alarm signal. If
a child process does not complete its execution in 5 second then parent process kills child process
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
// Global variable to track whether the child process has completed
int child_completed = 0;
// Signal handler for SIGCHLD (child process termination)
void sigchld_handler(int signum) {
if (signum == SIGCHLD) {
int status;
pid_t pid = wait(&status);
if (WIFEXITED(status)) {
printf("Child process %d completed with exit status: %d\n", pid, WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("Child process %d terminated by signal: %d\n", pid, WTERMSIG(status));
}
child_completed = 1;
}
}
// Signal handler for SIGALRM (timeout)
void sigalarm_handler(int signum) {
if (signum == SIGALRM) {
printf("Child process did not complete within the specified time. Killing the child process.\n");
kill(0, SIGKILL); // Kill the entire process group, including the child process
}
}
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: %s command [args...]\n", argv[0]);
return 1;
}
// Set up signal handler for SIGCHLD
signal(SIGCHLD, sigchld_handler);
// Set up signal handler for SIGALRM
signal(SIGALRM, sigalarm_handler);
pid_t child_pid;
// Create a child process
if ((child_pid = fork()) == -1) {
perror("fork");
return 1;
}
if (child_pid == 0) {
// Child process
execvp(argv[1], &argv[1]);
// execvp returns only if there is an error
perror("execvp");
exit(EXIT_FAILURE);
} else {
// Parent process
// Set an alarm for 5 seconds
alarm(5);
// Wait for the child process to complete or be killed
while (!child_completed) {
// Do nothing, just wait
}
}
return 0;
}
SLIP 4:
/*
Write a C program to find whether a given files passed through command line arguments are
present in current directory or not
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
// Check if filenames are provided
if (argc < 2) {
printf("Ohhh Sorry You are not proving arguments..");
return 1;
}
// Iterate through command line arguments
for (int i = 1; i < argc; ++i) {
FILE *file = fopen(argv[i], "r");
if (file != NULL) {
printf("%s is present in the current directory.\n", argv[i]);
fclose(file);
} else {
printf("%s is not present in the current directory.\n", argv[i]);
}
}
return 0;
}
/*In window:
PS C:\Bootstrap Program> gcc Slip4A.c -o Slip4A
PS C:\Bootstrap Program> ./Slip4A Slip4A.c
In Linux:
cc Slip4A.c
./a.out
Slip4A.c is present in the current directory.
*/
/*Write a C program which creates a child process and child process catches a signal SIGHUP,
SIGINT and SIGQUIT. The Parent process send a SIGHUP or SIGINT signal after every 3
seconds, at the end of 15 second parent send SIGQUIT signal to child and child terminates by
displaying message "My Papa has Killed me!!!”
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
void sighup_handler(int signum) {
if (signum == SIGHUP) {
printf("Child process received SIGHUP.\n");
}
}
void sigint_handler(int signum) {
if (signum == SIGINT) {
printf("Child process received SIGINT.\n");
}
}
void sigquit_handler(int signum) {
if (signum == SIGQUIT) {
printf("Child process received SIGQUIT. My Papa has killed me!!!\n");
exit(EXIT_SUCCESS);
}
}
int main() {
pid_t child_pid;
// Create a child process
if ((child_pid = fork()) == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (child_pid == 0) {
// Child process
// Set up signal handlers
signal(SIGHUP, sighup_handler);
signal(SIGINT, sigint_handler);
signal(SIGQUIT, sigquit_handler);
// Infinite loop to keep the child process running
while (1) {
sleep(1);
}
} else {
// Parent process
// Send SIGHUP or SIGINT to the child every 3 seconds for 12 seconds
for (int i = 0; i < 4; ++i) {
sleep(3);
if (i % 2 == 0) {
kill(child_pid, SIGHUP);
} else {
kill(child_pid, SIGINT);
}
}
// After 15 seconds, send SIGQUIT to terminate the child
sleep(3);
kill(child_pid, SIGQUIT);
// Wait for the child to terminate
wait(NULL);
}
return 0;
}
SLIP 5:
/*Read the current directory and
display the name of the files, no of files in current directory
*/
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *entry;
int file_count = 0;
// Open the current directory
if ((dir = opendir(".")) != NULL) {
// Iterate through directory entries
while ((entry = readdir(dir)) != NULL) {
// Display file name
printf("%s\n", entry->d_name);
// Count files
if (entry->d_type == DT_REG) {
file_count++;
}
}
// Close the directory
closedir(dir);
// Display the total number of files
printf("Total number of files: %d\n", file_count);
} else {
// Print an error message if opendir fails
perror("opendir");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/*
.
..
cinode.c
cinode.exe
h1.html
Slip1A.c
Slip1A.exe
Slip1B.c
Slip2A.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MESSAGE1 "Hello World"
#define MESSAGE2 "Hello SPPU"
#define MESSAGE3 "Linux is Funny"
int main() {
int pipe_fd[2];
pid_t child_pid;
// Create pipe
if (pipe(pipe_fd) == -1) {
perror("Pipe creation failed");
exit(EXIT_FAILURE);
}
// Fork a child process
if ((child_pid = fork()) == -1) {
perror("Fork failed");
exit(EXIT_FAILURE);
}
if (child_pid == 0) { // Child process
// Close read end of the pipe
close(pipe_fd[0]);
// Write messages to the pipe
write(pipe_fd[1], MESSAGE1, sizeof(MESSAGE1));
write(pipe_fd[1], MESSAGE2, sizeof(MESSAGE2));
write(pipe_fd[1], MESSAGE3, sizeof(MESSAGE3));
// Close write end of the pipe
close(pipe_fd[1]);
exit(EXIT_SUCCESS);
} else { // Parent process
// Close write end of the pipe
close(pipe_fd[1]);
char buffer[256];
// Read and display messages from the pipe
read(pipe_fd[0], buffer, sizeof(buffer));
printf("%s\n", buffer);
read(pipe_fd[0], buffer, sizeof(buffer));
printf("%s\n", buffer);
read(pipe_fd[0], buffer, sizeof(buffer));
printf("%s\n", buffer);
// Close read end of the pipe
close(pipe_fd[0]);
}
return 0;
}
/*
Write a C program to create an unnamed pipe. The child process will write following three
messages to pipe and parent process display it.
Message1 = “Hello World”
Message2 = “Hello SPPU”
Message3 = “Linux is Funny”
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
int pipe_fd[2];
pid_t child_pid;
// Create the pipe
if (pipe(pipe_fd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
// Create a child process
if ((child_pid = fork()) == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (child_pid == 0) {
// Child process
close(pipe_fd[0]); // Close the read end of the pipe
// Write messages to the pipe
const char *messages[] = {"Hello World\n", "Hello SPPU\n", "Linux is Funny\n"};
for (int i = 0; i < 3; ++i) {
write(pipe_fd[1], messages[i], strlen(messages[i]));
}
close(pipe_fd[1]); // Close the write end of the pipe in the child
} else {
// Parent process
close(pipe_fd[1]); // Close the write end of the pipe
// Read and display messages from the pipe
char buffer[1024];
ssize_t n;
while ((n = read(pipe_fd[0], buffer, sizeof(buffer))) > 0) {
write(STDOUT_FILENO, buffer, n);
}
close(pipe_fd[0]); // Close the read end of the pipe in the parent
wait(NULL); // Wait for the child to complete
}
return 0;
}
Slip 6
A
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <time.h>
int main() {
// Open the current directory
DIR *dir = opendir(".");
// Check if the directory opened successfully
if (dir == NULL) {
perror("Unable to open directory");
return 1;
}
// Read and display directory entries
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// Skip "." and ".." entries
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// Get file information
struct stat file_stat;
char filename[256];
snprintf(filename, sizeof(filename), "%s", entry->d_name);
if (stat(filename, &file_stat) == -1) {
perror("Error getting file information");
closedir(dir);
return 1;
}
// Check if the file was created in the 1st month
struct tm *creation_time = localtime(&file_stat.st_ctime);
if (creation_time->tm_mon + 1 == 1) {
printf("%s\n", entry->d_name);
}
}
// Close the directory
closedir(dir);
return 0;
}
B]
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/times.h>
#include <unistd.h>
int main() {
// Number of child processes to create
int n = 5; // You can change this to the desired number of child processes
clock_t start, end;
struct tms start_tms, end_tms;
// Record start time
start = times(&start_tms);
// Create n child processes
for (int i = 0; i < n; ++i) {
pid_t child_pid = fork();
if (child_pid == -1) {
perror("Fork failed");
exit(EXIT_FAILURE);
} else if (child_pid == 0) {
// Code for child process
printf("Child %d started\n", i + 1);
// Child-specific code goes here
printf("Child %d finished\n", i + 1);
exit(EXIT_SUCCESS);
}
}
// Wait for all child processes to terminate
for (int i = 0; i < n; ++i) {
wait(NULL);
}
// Record end time
end = times(&end_tms);
// Calculate total user and kernel mode time
clock_t user_time = end_tms.tms_utime - start_tms.tms_utime;
clock_t sys_time = end_tms.tms_stime - start_tms.tms_stime;
printf("Total User Time: %f seconds\n", (double)user_time / sysconf(_SC_CLK_TCK));
printf("Total Kernel Time: %f seconds\n", (double)sys_time / sysconf(_SC_CLK_TCK));
return 0;
}
Slip7
A
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main() {
// Open a file for writing (or create it if it doesn't exist)
int fileDescriptor = open("output.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fileDescriptor == -1) {
perror("Error opening file");
exit(EXIT_FAILURE);
}
// Redirect standard output to the file
if (dup2(fileDescriptor, STDOUT_FILENO) == -1) {
perror("Error redirecting standard output");
close(fileDescriptor);
exit(EXIT_FAILURE);
}
// Close the file descriptor, as dup2 duplicates the file descriptor
close(fileDescriptor);
// Now, standard output is redirected to the file
printf("This will be written to output.txt\n");
// Close standard output to prevent further writing to the file
fclose(stdout);
return 0;
}
B]
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
int pipe_fd[2];
pid_t child_ls_pid, child_wc_pid;
// Create pipe
if (pipe(pipe_fd) == -1) {
perror("Pipe creation failed");
exit(EXIT_FAILURE);
}
// Fork first child for ls -l
child_ls_pid = fork();
if (child_ls_pid == -1) {
perror("Fork failed");
exit(EXIT_FAILURE);
}
if (child_ls_pid == 0) {
// Child process for ls -l
close(pipe_fd[0]); // Close read end of the pipe
dup2(pipe_fd[1], STDOUT_FILENO); // Redirect standard output to the pipe write end
// Execute ls -l
execlp("ls", "ls", "-l", NULL);
perror("Exec failed");
exit(EXIT_FAILURE);
}
// Fork second child for wc -l
child_wc_pid = fork();
if (child_wc_pid == -1) {
perror("Fork failed");
exit(EXIT_FAILURE);
}
if (child_wc_pid == 0) {
// Child process for wc -l
close(pipe_fd[1]); // Close write end of the pipe
dup2(pipe_fd[0], STDIN_FILENO); // Redirect standard input to the pipe read end
// Execute wc -l
execlp("wc", "wc", "-l", NULL);
perror("Exec failed");
exit(EXIT_FAILURE);
}
// Close unused pipe ends in the parent process
close(pipe_fd[0]);
close(pipe_fd[1]);
// Wait for both child processes to finish
wait(NULL);
wait(NULL);
return 0;
}
Slip 8 A]
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main() {
// Open the file "output.txt" for writing, creating it if it doesn't exist,
// and truncating it to zero length if it already exists
int fileDescriptor = open("output.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (fileDescriptor == -1) {
perror("open");
exit(EXIT_FAILURE);
}
// Duplicate the file descriptor to stdout (file descriptor 1)
if (dup2(fileDescriptor, STDOUT_FILENO) == -1) {
perror("dup2");
exit(EXIT_FAILURE);
}
// Close the original file descriptor as it is no longer needed
close(f
Slip8 B]= Slip7 B]
Slip 10
A]
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
int pipefd[2];
pid_t child1, child2;
// Create a pipe
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
// Create the first child process
if ((child1 = fork()) == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (child1 == 0) { // Inside the first child process
close(pipefd[0]); // Close unused read end
// Redirect stdout to the write end of the pipe
dup2(pipefd[1], STDOUT_FILENO);
// Execute the first command (e.g., "ls")
execlp("ls", "ls", (char *)NULL);
// If execlp fails
perror("execlp");
exit(EXIT_FAILURE);
} else { // Inside the parent process
// Create the second child process
if ((child2 = fork()) == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (child2 == 0) { // Inside the second child process
close(pipefd[1]); // Close unused write end
// Redirect stdin to the read end of the pipe
dup2(pipefd[0], STDIN_FILENO);
// Execute the second command (e.g., "wc -l")
execlp("wc", "wc", "-l", (char *)NULL);
// If execlp fails
perror("execlp");
exit(EXIT_FAILURE);
} else { // Inside the parent process
// Close both ends of the pipe in the parent
close(pipefd[0]);
close(pipefd[1]);
// Wait for both child processes to finish
waitpid(child1, NULL, 0);
waitpid(child2, NULL, 0);
}
}
return 0;
}
B]
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define BUFFER_SIZE 1024
int main() {
int pipefd[2];
pid_t child_pid;
char buffer[BUFFER_SIZE];
// Create a pipe
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
// Create the child process
if ((child_pid = fork()) == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (child_pid == 0) { // Inside the child process
close(pipefd[1]); // Close unused write end
// Read from the pipe and print the received data
ssize_t bytesRead = read(pipefd[0], buffer, sizeof(buffer));
if (bytesRead == -1) {
perror("read");
exit(EXIT_FAILURE);
}
// Display the data read from the pipe
printf("Child Process: Received data from parent: %.*s\n", (int)bytesRead, buffer);
// Close the read end of the pipe in the child
close(pipefd[0]);
} else { // Inside the parent process
close(pipefd[0]); // Close unused read end
// Write data into the pipe
const char *message = "Hello, child! This is from the parent process.";
ssize_t bytesWritten = write(pipefd[1], message, strlen(message));
if (bytesWritten == -1) {
perror("write");
exit(EXIT_FAILURE);
}
// Close the write end of the pipe in the parent
close(pipefd[1]);
// Wait for the child process to finish
waitpid(child_pid, NULL, 0);
}
return 0;
}
___________________________________
Slip 11 A]
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
void print_limits() {
struct rlimit limits;
// Get the current resource limits for the process
if (getrlimit(RLIMIT_NOFILE, &limits) == -1) {
perror("getrlimit");
exit(EXIT_FAILURE);
}
// Display the current file limit
printf("Current file limit: %lld\n", (long long)limits.rlim_cur);
// Set a new file limit (e.g., 1024)
limits.rlim_cur = 1024;
// Set the new file limit for the process
if (setrlimit(RLIMIT_NOFILE, &limits) == -1) {
perror("setrlimit");
exit(EXIT_FAILURE);
}
// Get the updated resource limits
if (getrlimit(RLIMIT_NOFILE, &limits) == -1) {
perror("getrlimit");
exit(EXIT_FAILURE);
}
// Display the updated file limit
printf("Updated file limit: %lld\n", (long long)limits.rlim_cur);
}
int main() {
print_limits();
return 0;
}
Slip 11 B] = Slip 8 a]
Slip 12 A]
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
pid_t child_pid;
int status;
// Fork a child process
if ((child_pid = fork()) == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (child_pid == 0) { // Inside the child process
printf("Child Process: This is the child process\n");
// Simulate a child process exit with status 42
exit(42);
} else { // Inside the parent process
// Wait for the child process to terminate and get its exit status
if (waitpid(child_pid, &status, 0) == -1) {
perror("waitpid");
exit(EXIT_FAILURE);
}
if (WIFEXITED(status)) {
// The child process terminated normally
printf("Parent Process: Child process exited with status: %d\n", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
// The child process terminated due to a signal
printf("Parent Process: Child process terminated by signal: %d\n", WTERMSIG(status));
}
}
return 0;
}
B]
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#define MAX_FILES 50
// Structure to store file information
struct FileInfo {
char name[256];
off_t size;
};
// Comparison function for qsort to sort FileInfo array by size
int compareSize(const void *a, const void *b) {
return ((struct FileInfo*)a)->size - ((struct FileInfo*)b)->size;
}
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: %s <file1> <file2> ... <fileN>\n", argv[0]);
exit(EXIT_FAILURE);
}
struct FileInfo files[MAX_FILES];
int fileCount = 0;
// Iterate through command line arguments (file names)
for (int i = 1; i < argc && fileCount < MAX_FILES; ++i) {
struct stat st;
// Get file information
if (stat(argv[i], &st) == 0) {
if (S_ISREG(st.st_mode)) { // Check if it is a regular file
// Copy file name and size to FileInfo structure
strncpy(files[fileCount].name, argv[i], sizeof(files[fileCount].name));
files[fileCount].size = st.st_size;
++fileCount;
} else {
fprintf(stderr, "Skipping non-regular file: %s\n", argv[i]);
}
} else {
perror("stat");
}
}
// Sort files array based on size
qsort(files, fileCount, sizeof(struct FileInfo), compareSize);
// Display filenames in ascending order of sizes
printf("File Names in Ascending Order of Sizes:\n");
for (int i = 0; i < fileCount; ++i) {
printf("%s: %lld bytes\n", files[i].name, (long long)files[i].size);
}
return 0;
}
Slip 13 a]
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
volatile sig_atomic_t counter = 0;
void handle_sigusr1(int signo) {
// Custom signal handler for SIGUSR1
printf("Child Process: Received SIGUSR1 signal. Suspending...\n");
pause(); // Suspend the process until SIGCONT is received
printf("Child Process: Resumed. Continuing...\n");
}
int main() {
pid_t child_pid;
// Install a custom signal handler for SIGUSR1
signal(SIGUSR1, handle_sigusr1);
// Fork a child process
if ((child_pid = fork()) == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (child_pid == 0) { // Inside the child process
while (1) {
// Child process main loop
printf("Child Process: Counter = %d\n", counter);
sleep(1);
counter++;
}
} else { // Inside the parent process
// Wait for a moment to let the child start
sleep(2);
// Send SIGUSR1 to the child to trigger suspension
kill(child_pid, SIGUSR1);
// Wait for a moment to observe the child being suspended
sleep(3);
// Send SIGCONT to the child to resume it
kill(child_pid, SIGCONT);
// Let the child run for a while
sleep(5);
// Send SIGTERM to terminate the child process
kill(child_pid, SIGTERM);
}
return 0;
}
B]
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <prefix>\n", argv[0]);
exit(EXIT_FAILURE);
}
char *prefix = argv[1];
// Open the current directory
DIR *dir = opendir(".");
if (dir == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
// Read the directory entries
struct dirent *entry;
printf("Files with prefix \"%s\":\n", prefix);
while ((entry = readdir(dir)) != NULL) {
// Check if the entry matches the prefix
if (strncmp(entry->d_name, prefix, strlen(prefix)) == 0) {
printf("%s\n", entry->d_name);
}
}
// Close the directory
closedir(dir);
return 0;
}
Slip 14 A]
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
int main() {
long long n;
// Accept size 'n' from the user
printf("Enter the size threshold in bytes: ");
scanf("%lld", &n);
// Open the current directory
DIR *dir = opendir(".");
if (dir == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
// Read the directory entries
struct dirent *entry;
printf("Files with size greater than %lld bytes:\n", n);
while ((entry = readdir(dir)) != NULL) {
// Get the file information
struct stat fileStat;
if (stat(entry->d_name, &fileStat) == -1) {
perror("stat");
continue;
}
// Check if it's a regular file and its size is greater than n
if (S_ISREG(fileStat.st_mode) && fileStat.st_size > n) {
printf("%s (%lld bytes)\n", entry->d_name, (long long)fileStat.st_size);
}
}
// Close the directory
closedir(dir);
return 0;
}
Slip 14 b ] =Slip 2 a]
Slip 15 A] = Slip 14 A]
Slip 15 B] = Slip 3 B ]
==============================
Some Shortcuts:
Slip 1
Q1. Take multiple files as Command Line Arguments and print their inode numbers and file
types.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <file1> <file2> ... <fileN>\n", argv[0]);
return 1;
}
for (int i = 1; i < argc; i++) {
struct stat fileStat;
if (stat(argv[i], &fileStat) < 0) {
fprintf(stderr, "Error accessing file %s: %s\n", argv[i], strerror(errno));
continue;
}
printf("File: %s\n", argv[i]);
printf("Inode Number: %ld\n", (long)fileStat.st_ino);
if (S_ISREG(fileStat.st_mode)) {
printf("File Type: Regular file\n");
} else if (S_ISDIR(fileStat.st_mode)) {
printf("File Type: Directory\n");
} else if (S_ISLNK(fileStat.st_mode)) {
printf("File Type: Symbolic Link\n");
} else if (S_ISCHR(fileStat.st_mode)) {
printf("File Type: Character Device\n");
} else if (S_ISBLK(fileStat.st_mode)) {
printf("File Type: Block Device\n");
} else if (S_ISFIFO(fileStat.st_mode)) {
printf("File Type: FIFO/Named Pipe\n");
} else if (S_ISSOCK(fileStat.st_mode)) {
printf("File Type: Socket\n");
} else {
printf("File Type: Unknown\n");
}
printf("\n");
}
return 0;
}
Output:
File: file1.txt
Inode Number: 123456
File Type: Regular file
File: file2.txt
Inode Number: 789012
File Type: Regular file
File: directory
Inode Number: 345678
File Type: Directory
Q2. Write a C program to send SIGALRM signal by child process to parent process and
parent process make a provision to catch the signal and display alarm is fired.(Use Kill, fork,
signal and sleep system call).
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
void handle_alarm(int signum) {
if (signum == SIGALRM) {
printf("Alarm is fired!\n");
}
}
int main() {
pid_t pid;
signal(SIGALRM, handle_alarm); // Registering the signal handler
pid = fork();
if (pid < 0) {
perror("Fork failed");
exit(EXIT_FAILURE);
} else if (pid == 0) { // Child process
sleep(2); // Waiting for 2 seconds
kill(getppid(), SIGALRM); // Sending SIGALRM signal to the parent
} else { // Parent process
printf("Waiting for alarm...\n");
while(1) {
// Parent process waits indefinitely for the signal
// The signal handler will execute upon receiving SIGALRM
}
}
return 0;
}
Output:
Waiting for alarm...
Alarm is fired!
Slip 2
Q1. Write a C program to find file properties such as inode number, number of hard link, File
permissions, File size, File access and modification time and so on of a given file using stat()
system call.
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <filename>\n", argv[0]);
return 1;
}
struct stat fileStat;
if (stat(argv[1], &fileStat) < 0) {
fprintf(stderr, "Error accessing file %s: %s\n", argv[1], strerror(errno));
return 1;
}
printf("File: %s\n", argv[1]);
printf("Inode Number: %ld\n", (long)fileStat.st_ino);
printf("Number of Hard Links: %ld\n", (long)fileStat.st_nlink);
printf("File Permissions: ");
printf((S_ISDIR(fileStat.st_mode)) ? "d" : "-");
printf((fileStat.st_mode & S_IRUSR) ? "r" : "-");
printf((fileStat.st_mode & S_IWUSR) ? "w" : "-");
printf((fileStat.st_mode & S_IXUSR) ? "x" : "-");
printf((fileStat.st_mode & S_IRGRP) ? "r" : "-");
printf((fileStat.st_mode & S_IWGRP) ? "w" : "-");
printf((fileStat.st_mode & S_IXGRP) ? "x" : "-");
printf((fileStat.st_mode & S_IROTH) ? "r" : "-");
printf((fileStat.st_mode & S_IWOTH) ? "w" : "-");
printf((fileStat.st_mode & S_IXOTH) ? "x\n" : "-\n");
printf("File Size: %ld bytes\n", (long)fileStat.st_size);
printf("Last Access Time: %s", ctime(&fileStat.st_atime));
printf("Last Modification Time: %s", ctime(&fileStat.st_mtime));
return 0;
}
Output:
File: example.txt
Inode Number: 123456
Number of Hard Links: 1
File Permissions: -rw-r--r--
File Size: 1024 bytes
Last Access Time: Mon Jan 10 15:30:00 2023
Last Modification Time: Fri Dec 15 09:45:00 2023
Q2. Write a C program that catches the ctrl-c (SIGINT) signal for the first time and display
the appropriate message and exits on pressing ctrl-c again.
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
int count = 0;
void handle_sigint(int signum) {
if (signum == SIGINT) {
if (count == 0) {
printf("\nCaught SIGINT signal. Press Ctrl+C again to exit.\n");
count++;
} else {
printf("\nReceived second SIGINT. Exiting...\n");
exit(EXIT_SUCCESS);
}
}
}
int main() {
signal(SIGINT, handle_sigint);
printf("Press Ctrl+C to trigger SIGINT signal.\n");
while(1) {
// Program continues running and waiting for SIGINT
}
return 0;
}
Slip 3
Q1. Print the type of file and inode number where file name accepted through Command
Line.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <filename>\n", argv[0]);
return 1;
}
struct stat fileStat;
if (stat(argv[1], &fileStat) < 0) {
fprintf(stderr, "Error accessing file %s: %s\n", argv[1], strerror(errno));
return 1;
}
printf("File: %s\n", argv[1]);
printf("Inode Number: %ld\n", (long)fileStat.st_ino);
if (S_ISREG(fileStat.st_mode)) {
printf("File Type: Regular file\n");
} else if (S_ISDIR(fileStat.st_mode)) {
printf("File Type: Directory\n");
} else if (S_ISLNK(fileStat.st_mode)) {
printf("File Type: Symbolic Link\n");
} else if (S_ISCHR(fileStat.st_mode)) {
printf("File Type: Character Device\n");
} else if (S_ISBLK(fileStat.st_mode)) {
printf("File Type: Block Device\n");
} else if (S_ISFIFO(fileStat.st_mode)) {
printf("File Type: FIFO/Named Pipe\n");
} else if (S_ISSOCK(fileStat.st_mode)) {
printf("File Type: Socket\n");
} else {
printf("File Type: Unknown\n");
}
return 0;
}
Output :
example.txt is a regular file:
File: example.txt
Inode Number: 123456
File Type: Regular file
example.txt is a directory file:
File: example.txt
Inode Number: 123456
File Type: Directory file
Q2. Write a C program which creates a child process to run linux/ unix command or any user
defined program. The parent process set the signal handler for death of child signal and
Alarm signal. If a child process does not complete its execution in 5 second then parent
process kills child process.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
void child_handler(int signum) {
if (signum == SIGCHLD) {
printf("Child process has terminated.\n");
}
}
void alarm_handler(int signum) {
if (signum == SIGALRM) {
printf("Child process exceeded time limit. Killing...\n");
kill(getpid(), SIGKILL); // Kill the current process
}
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <command>\n", argv[0]);
return 1;
}
signal(SIGCHLD, child_handler);
signal(SIGALRM, alarm_handler);
pid_t pid = fork();
if (pid < 0) {
perror("Fork failed");
exit(EXIT_FAILURE);
} else if (pid == 0) { // Child process
execvp(argv[1], &argv[1]); // Execute the command
perror("Execution failed");
exit(EXIT_FAILURE);
} else { // Parent process
alarm(5); // Set alarm for 5 seconds
// Wait for the child process to terminate
wait(NULL);
alarm(0); // Cancel the alarm
}
return 0;
}
Output :
Child process has terminated.
Slip 4
Q.1) Write a C program to find whether a given files passed through command line
arguments are present in current directory or not.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <file1> <file2> ... <fileN>\n", argv[0]);
return 1;
}
for (int i = 1; i < argc; i++) {
if (access(argv[i], F_OK) != -1) {
printf("%s exists in the current directory.\n", argv[i]);
} else {
printf("%s does not exist in the current directory.\n", argv[i]);
}
}
return 0;
}
Output :
./program_name file1.txt file2.txt
file1.txt exists in the current directory.
Q.2) Write a C program which creates a child process and child process catches a signal
SIGHUP, SIGINT and SIGQUIT. The Parent process send a SIGHUP or SIGINT signal after
every 3 seconds, at the end of 15 second parent send SIGQUIT signal to child and child
terminates by displaying message "My Papa has Killed me!!!”.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
int kill_child = 0;
void child_handler(int signum) {
if (signum == SIGHUP) {
printf("Child received SIGHUP from parent.\n");
} else if (signum == SIGINT) {
printf("Child received SIGINT from parent.\n");
} else if (signum == SIGQUIT) {
printf("My Papa has Killed me!!!\n");
exit(EXIT_SUCCESS);
}
}
int main() {
pid_t pid = fork();
if (pid < 0) {
perror("Fork failed");
exit(EXIT_FAILURE);
} else if (pid == 0) { // Child process
signal(SIGHUP, child_handler);
signal(SIGINT, child_handler);
signal(SIGQUIT, child_handler);
while(1) {
// Child process continues running and handling signals
}
} else { // Parent process
int counter = 0;
while (counter < 5) { // Sending signals for 15 seconds (5 * 3 seconds)
sleep(3);
if (!kill_child) {
kill(pid, SIGHUP); // Send SIGHUP signal
} else {
kill(pid, SIGINT); // Send SIGINT signal
}
counter++;
if (counter == 5) {
kill(pid, SIGQUIT); // Send SIGQUIT signal after 15 seconds
}
kill_child = !kill_child;
}
wait(NULL); // Wait for child to terminate
}
return 0;
}
Output :
Child received SIGHUP from parent.
Child received SIGINT from parent.
Child received SIGHUP from parent.
Child received SIGINT from parent.
Child received SIGHUP from parent.
Child received SIGINT from parent.
Child received SIGHUP from parent.
Child received SIGINT from parent.
Child received SIGHUP from parent.
My Papa has Killed me!!!
Slip 5
Q.1) Read the current directory and display the name of the files, no of files in current
directory.
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
int main() {
DIR *directory;
struct dirent *entry;
int file_count = 0;
// Open the current directory
directory = opendir(".");
if (directory == NULL) {
perror("Unable to open directory");
return EXIT_FAILURE;
}
// Read directory entries and display file names
while ((entry = readdir(directory)) != NULL) {
printf("%s\n", entry->d_name);
file_count++;
}
closedir(directory);
printf("\nTotal files in current directory: %d\n", file_count);
return EXIT_SUCCESS;
}
Output :
file1.txt
file2.jpg
folder1
folder2
program.c
Q.2) Write a C program to create an unnamed pipe. The child process will write following
three messages to pipe and parent process display it.
Message1 = “Hello World”
Message2 = “Hello SPPU”
Message3 = “Linux is Funny”
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define MSG_SIZE 100
int main() {
int pipefd[2];
pid_t pid;
char message[3][MSG_SIZE] = {
"Hello World",
"Hello SPPU",
"Linux is Funny"
};
if (pipe(pipefd) == -1) {
perror("Pipe creation failed");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid < 0) {
perror("Fork failed");
exit(EXIT_FAILURE);
} else if (pid == 0) { // Child process
close(pipefd[0]); // Close reading end of pipe in child
for (int i = 0; i < 3; i++) {
write(pipefd[1], message[i], strlen(message[i]) + 1);
}
close(pipefd[1]); // Close writing end of pipe in child
} else { // Parent process
close(pipefd[1]); // Close writing end of pipe in parent
char buffer[MSG_SIZE];
while (read(pipefd[0], buffer, MSG_SIZE) > 0) {
printf("Message received: %s\n", buffer);
}
close(pipefd[0]); // Close reading end of pipe in parent
}
return 0;
}
Output :
Message received: Hello World
Message received: Hello SPPU
Message received: Linux is Funny
Slip 6
Q.1) Display all the files from current directory which are created in particular month.
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <time.h>
int main() {
DIR *directory;
struct dirent *entry;
struct stat fileStat;
time_t now = time(NULL);
struct tm *current_time = localtime(&now);
int current_month = current_time->tm_mon + 1; // Month is zero-based in struct tm
// Open the current directory
directory = opendir(".");
if (directory == NULL) {
perror("Unable to open directory");
return EXIT_FAILURE;
}
// Read directory entries and display files created in a specific month
printf("Files created in current month (%d):\n", current_month);
while ((entry = readdir(directory)) != NULL) {
if (stat(entry->d_name, &fileStat) == 0) {
struct tm *file_time = localtime(&fileStat.st_ctime);
int file_month = file_time->tm_mon + 1; // Month is zero-based in struct tm
if (file_month == current_month) {
printf("%s\n", entry->d_name);
}
}
}
closedir(directory);
return EXIT_SUCCESS;
}
Output :
Files created in current month (12):
file1.txt
Q.2)Write a C program to create n child processes. When all n child processes terminates,
Display total cumulative time children spent in user and kernel mode.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <number_of_children>\n", argv[0]);
return 1;
}
int num_children = atoi(argv[1]);
struct rusage usage;
int status;
pid_t pid;
for (int i = 0; i < num_children; i++) {
pid = fork();
if (pid < 0) {
perror("Fork failed");
return 1;
} else if (pid == 0) { // Child process
// Perform child's task
sleep(1);
exit(EXIT_SUCCESS);
}
}
// Wait for all child processes to terminate
while ((pid = wait(&status)) > 0);
// Get resource usage statistics for all children
if (getrusage(RUSAGE_CHILDREN, &usage) == -1) {
perror("getrusage failed");
return 1;
}
// Display total cumulative time spent by children in user and kernel mode
printf("Total user time spent by children: %ld.%06ld seconds\n", usage.ru_utime.tv_sec,
usage.ru_utime.tv_usec);
printf("Total kernel time spent by children: %ld.%06ld seconds\n", usage.ru_stime.tv_sec,
usage.ru_stime.tv_usec);
return 0;
}
Output :
Total user time spent by children: 0.000002 seconds
Total kernel time spent by children: 0.000000 seconds
Slip 7
Q.1) Write a C Program that demonstrates redirection of standard output to a file.
#include <stdio.h>
int main() {
// File pointer to store the redirected output
FILE *file_ptr;
// Open the file in write mode to redirect output
file_ptr = freopen("output.txt", "w", stdout);
if (file_ptr == NULL) {
perror("Error opening file");
return 1;
}
// Printing to stdout (redirected to file)
printf("This output is redirected to a file.\n");
// Closing the file pointer
fclose(file_ptr);
return 0;
}
Output :
This output is redirected to a file.
Q.2) Implement the following unix/linux command (use fork, pipe and exec system call)
ls –l | wc –l
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
int pipe_fd[2];
if (pipe(pipe_fd) == -1) {
perror("Pipe creation failed");
exit(EXIT_FAILURE);
}
pid_t pid = fork();
if (pid < 0) {
perror("Fork failed");
exit(EXIT_FAILURE);
} else if (pid == 0) { // Child process
close(pipe_fd[0]); // Close reading end of pipe in child
dup2(pipe_fd[1], STDOUT_FILENO); // Redirect stdout to pipe write end
// Execute ls -l command
execlp("ls", "ls", "-l", NULL);
// execlp will not return unless there's an error
perror("exec ls -l failed");
exit(EXIT_FAILURE);
} else { // Parent process
close(pipe_fd[1]); // Close writing end of pipe in parent
dup2(pipe_fd[0], STDIN_FILENO); // Redirect stdin to pipe read end
// Execute wc -l command
execlp("wc", "wc", "-l", NULL);
// execlp will not return unless there's an error
perror("exec wc -l failed");
exit(EXIT_FAILURE);
}
return 0;
}
Output :
7
Slip 8
Q.1) Write a C program that redirects standard output to a file output.txt. (use of dup and
open system call).
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int file_descriptor;
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; // File permissions
// Open file for writing (creating if it doesn't exist)
file_descriptor = open("output.txt", O_WRONLY | O_CREAT | O_TRUNC, mode);
if (file_descriptor < 0) {
perror("Error opening file");
return 1;
}
// Redirect standard output to the file
if (dup2(file_descriptor, STDOUT_FILENO) == -1) {
perror("Error redirecting output");
return 1;
}
// Close the file descriptor
close(file_descriptor);
// Printing to stdout (redirected to file)
printf("This output is redirected to a file using dup and open system calls.\n");
return 0;
}
Output :
This output is redirected to a file using dup and open system calls.
Q.2) Implement the following unix/linux command (use fork, pipe and exec system call)
ls –l | wc –l.
Same As Slip 7
Slip 9
Q.1) Generate parent process to write unnamed pipe and will read from it.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#define MSG_SIZE 100
int main() {
int pipe_fd[2];
pid_t pid;
char message[MSG_SIZE] = "Hello from parent!";
if (pipe(pipe_fd) == -1) {
perror("Pipe creation failed");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid < 0) {
perror("Fork failed");
exit(EXIT_FAILURE);
} else if (pid == 0) { // Child process
close(pipe_fd[1]); // Close writing end of pipe in child
char buffer[MSG_SIZE];
read(pipe_fd[0], buffer, MSG_SIZE);
printf("Child received: %s\n", buffer);
close(pipe_fd[0]); // Close reading end of pipe in child
} else { // Parent process
close(pipe_fd[0]); // Close reading end of pipe in parent
write(pipe_fd[1], message, sizeof(message));
close(pipe_fd[1]); // Close writing end of pipe in parent
}
return 0;
}
Output :
Child received: Hello from parent!
Slip 10
Q.1) Write a program that illustrates how to execute two commands concurrently with a
pipe.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
int pipe_fd[2];
if (pipe(pipe_fd) == -1) {
perror("Pipe creation failed");
exit(EXIT_FAILURE);
}
pid_t pid = fork();
if (pid < 0) {
perror("Fork failed");
exit(EXIT_FAILURE);
} else if (pid == 0) { // Child process 1 (writes to pipe)
close(pipe_fd[0]); // Close reading end of pipe in child 1
dup2(pipe_fd[1], STDOUT_FILENO); // Redirect stdout to pipe write end
// Execute command 1 (e.g., ls -l)
execlp("ls", "ls", "-l", NULL);
// execlp will not return unless there's an error
perror("exec command 1 failed");
exit(EXIT_FAILURE);
} else { // Parent process (reads from pipe)
close(pipe_fd[1]); // Close writing end of pipe in parent
pid_t pid2 = fork();
if (pid2 < 0) {
perror("Fork failed");
exit(EXIT_FAILURE);
} else if (pid2 == 0) { // Child process 2 (reads from pipe)
dup2(pipe_fd[0], STDIN_FILENO); // Redirect stdin to pipe read end
// Execute command 2 (e.g., wc -l)
execlp("wc", "wc", "-l", NULL);
// execlp will not return unless there's an error
perror("exec command 2 failed");
exit(EXIT_FAILURE);
} else { // Parent process
close(pipe_fd[0]); // Close reading end of pipe in parent
// Wait for both child processes to finish
wait(NULL);
wait(NULL);
}
}
return 0;
}
Output :
total 12
drwxr-xr-x 3 user user 4096 Jun 3 13:58 directory1
-rw-r--r-- 1 user user 164 Jun 3 13:59 file1.txt
drwxr-xr-x 2 user user 4096 Jun 3 13:58 directory2
Slip 11
Q.1) Write a C program to get and set the resource limits such as files, memory associated
with a process.
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
int main() {
struct rlimit limit;
// Get current resource limits for the process (for example, files limit)
if (getrlimit(RLIMIT_NOFILE, &limit) == -1) {
perror("getrlimit failed");
return EXIT_FAILURE;
}
printf("Current files limit: soft=%ld, hard=%ld\n", limit.rlim_cur, limit.rlim_max);
// Modify the resource limit (for example, increase files limit)
limit.rlim_cur = 1000; // Change the soft limit
limit.rlim_max = 1500; // Change the hard limit
if (setrlimit(RLIMIT_NOFILE, &limit) == -1) {
perror("setrlimit failed");
return EXIT_FAILURE;
}
printf("New files limit: soft=%ld, hard=%ld\n", limit.rlim_cur, limit.rlim_max);
return EXIT_SUCCESS;
}
Output :
Current files limit: soft=1024, hard=4096
New files limit: soft=1000, hard=1500
Slip 12
Q.1) Write a C program that print the exit status of a terminated child process.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid < 0) {
perror("Fork failed");
exit(EXIT_FAILURE);
} else if (pid == 0) { // Child process
// Perform some task in the child process
printf("Child process executing...\n");
exit(42); // Child process exits with status 42
} else { // Parent process
int status;
waitpid(pid, &status, 0); // Wait for the child process to terminate
if (WIFEXITED(status)) {
printf("Child process exited normally with status: %d\n", WEXITSTATUS(status));
} else {
printf("Child process exited abnormally\n");
}
}
return 0;
}
Output :
Child process executing...
Child process exited normally with status: 42
Q.2) Write a C program which receives file names as command line arguments and display
those filenames in ascending order according to their sizes. I) (e.g $ a.out a.txt b.txt c.txt, …)
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#define MAX_FILES 50
#define MAX_FILENAME_LENGTH 100
// Structure to hold file information
struct FileInfo {
char filename[MAX_FILENAME_LENGTH];
off_t size;
};
// Comparator function for qsort
int compare(const void *a, const void *b) {
return ((struct FileInfo *)a)->size - ((struct FileInfo *)b)->size;
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <file1> <file2> ... <fileN>\n", argv[0]);
return 1;
}
struct FileInfo files[MAX_FILES];
int num_files = argc - 1;
if (num_files > MAX_FILES) {
printf("Exceeded maximum number of files (%d)\n", MAX_FILES);
return 1;
}
// Get file sizes
for (int i = 0; i < num_files; ++i) {
struct stat fileStat;
if (stat(argv[i + 1], &fileStat) == -1) {
perror("stat");
return 1;
}
strncpy(files[i].filename, argv[i + 1], MAX_FILENAME_LENGTH - 1);
files[i].filename[MAX_FILENAME_LENGTH - 1] = '\0';
files[i].size = fileStat.st_size;
}
// Sort files based on size
qsort(files, num_files, sizeof(struct FileInfo), compare);
// Display filenames in ascending order of their sizes
printf("Files sorted by size (ascending order):\n");
for (int i = 0; i < num_files; ++i) {
printf("%s - %lld bytes\n", files[i].filename, (long long)files[i].size);
}
return 0;
}
Output :
Files sorted by size (ascending order):
file3.txt - 500 bytes
file1.txt - 1000 bytes
file2.txt - 2000 bytes
Slip 13
Q.1) Write a C program that illustrates suspending and resuming processes using signals.
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
void sig_handler(int signo) {
if (signo == SIGUSR1) {
printf("Received SIGUSR1 - Suspending the process\n");
raise(SIGSTOP); // Suspend the process
} else if (signo == SIGUSR2) {
printf("Received SIGUSR2 - Resuming the process\n");
}
}
int main() {
if (signal(SIGUSR1, sig_handler) == SIG_ERR || signal(SIGUSR2, sig_handler) ==
SIG_ERR) {
perror("Signal setup failed");
return EXIT_FAILURE;
}
printf("Waiting for signals...\n");
while (1) {
sleep(1); // Continuously wait for signals
}
return 0;
}
Output :
Waiting for signals...
Received SIGUSR1 - Suspending the process.
Q.2) Write a C program that a string as an argument and return all the files that begins with
that name in the current directory. For example > ./a.out foo will return all file names that
begins with foo.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <string>\n", argv[0]);
return 1;
}
DIR *dir;
struct dirent *entry;
if ((dir = opendir(".")) == NULL) {
perror("opendir() failed");
return 1;
}
printf("Files starting with '%s':\n", argv[1]);
while ((entry = readdir(dir)) != NULL) {
if (strncmp(entry->d_name, argv[1], strlen(argv[1])) == 0) {
printf("%s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
Output :
Files starting with 'foo':
foo1.txt
foo2.txt
foobar.txt
Slip 14
Q.1) Display all the files from current directory whose size is greater that n Bytes Where n is
accept from user.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
int main() {
long n;
printf("Enter the size in bytes: ");
scanf("%ld", &n);
DIR *dir;
struct dirent *entry;
struct stat fileStat;
if ((dir = opendir(".")) == NULL) {
perror("opendir() failed");
return 1;
}
printf("Files with size greater than %ld bytes:\n", n);
while ((entry = readdir(dir)) != NULL) {
if (stat(entry->d_name, &fileStat) == -1) {
perror("stat");
return 1;
}
if (S_ISREG(fileStat.st_mode) && fileStat.st_size > n) {
printf("%s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
Output :
Enter the size in bytes: 100
Files with size greater than 100 bytes:
file2.txt
file4.txt
Slip 15
Q.1) Display all the files from current directory whose size is greater that n Bytes Where n is
accept from user.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
int main() {
long n;
printf("Enter the size in bytes: ");
scanf("%ld", &n);
DIR *dir;
struct dirent *entry;
struct stat fileStat;
if ((dir = opendir(".")) == NULL) {
perror("opendir() failed");
return 1;
}
printf("Files with size greater than %ld bytes:\n", n);
while ((entry = readdir(dir)) != NULL) {
if (stat(entry->d_name, &fileStat) == -1) {
perror("stat");
return 1;
}
if (S_ISREG(fileStat.st_mode) && fileStat.st_size > n) {
printf("%s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
Output :
Enter the size in bytes: 1000
Files with size greater than 1000 bytes:
file2.txt
file4.txt
Note : All Other Remaining Slips Ques Are Same As Above Slips Ques.
s
s
s
s
s
Comments
Post a Comment
hey