Assignment1 Os 2
Assignment1 Os 2
Write a C program that behaves like a shell which displays the command prompt ‘myshell$’. It
Accepts the command, tokenize the command line and execute it by creating the child process.
Myshell$ count c filename: It will display the number of characters in given file
Myshell$ count w filename: It will display the number of words in given file
Myshell$ count l filename: It will display the number of lines in given file
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
Pid_t pid;
Pid = fork();
If (pid < 0) {
Perror(“Fork failed”);
Exit(1);
} else if (pid == 0) {
// Child process
Perror(“Execution failed”);
Exit(1);
}
} else {
// Parent process
Wait(NULL);
Int main() {
Char input[MAX_INPUT_SIZE];
While (1) {
Printf(“myshell$ “);
Int I = 0;
Tokens[i++] = token;
Tokens[i] = NULL;
If (I > 0) {
If (strcmp(tokens[0], “count”) == 0) {
If (I != 3) {
} else {
If (file == NULL) {
Exit(1);
Int count = 0;
Char c;
If (command[0] == ‘c’) {
Count++;
If (c == ‘ ‘ || c == ‘\n’ || c == ‘\t’) {
Count++;
If (c == ‘\n’) {
Count++;
Fclose(file);
} else {
executeCommand(tokens);
}
}
Return 0;
}
Set B
Write a C program that behaves like a shell which displays the command prompt ‘myshell$’. It
Accepts the command, tokenize the command line and execute it by creating the child process.
Myshell$ list n dirname: It will count the number of entries in a given directory.
Myshell$ list I dirname: It will display filenames and their inode number for the files in a given
Directory.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
Pid_t pid;
Pid = fork();
If (pid < 0) {
Perror(“Fork failed”);
Exit(1);
} else if (pid == 0) {
// Child process
Perror(“Execution failed”);
Exit(1);
} else {
// Parent process
Wait(NULL);
DIR *dir;
Dir = opendir(dirname);
If (dir == NULL) {
Exit(1);
Char path[1024];
Perror(“Failed to stat”);
Exit(1);
If (strcmp(option, “f”) == 0) {
If (S_ISREG(filestat.st_mode)) {
Printf(“%s\n”, entry->d_name);
}
Printf(“%s\n”, entry->d_name);
If (S_ISREG(filestat.st_mode)) {
Closedir(dir);
Int main() {
Char input[MAX_INPUT_SIZE];
While (1) {
Printf(“myshell$ “);
Int I = 0;
Tokens[i++] = token;
Tokens[i] = NULL;
If (I > 0) {
If (strcmp(tokens[0], “list”) == 0) {
// Handle ‘list’ command
If (I != 3) {
} else {
} else {
listFiles(dirname, option);
} else {
executeCommand(tokens);
Return 0;