Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
88 views

Unix Programs

The document contains code snippets in C and shell scripting to implement various file system operations like listing files in a directory, reading file contents, copying files, simulating grep command etc. It also includes code for signal handling, process management using pipes, comparing command line arguments and sorting numbers.

Uploaded by

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

Unix Programs

The document contains code snippets in C and shell scripting to implement various file system operations like listing files in a directory, reading file contents, copying files, simulating grep command etc. It also includes code for signal handling, process management using pipes, comparing command line arguments and sorting numbers.

Uploaded by

Sidhant Powar
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 8

/*

* C Program to List Files in Directory


*/
#include <dirent.h>
#include <stdio.h>

int main(void)
{
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d)
{
while ((dir = readdir(d)) != NULL)
{
printf("%s\n", dir->d_name);
}
closedir(d);
}
return(0);
}
//Write a program to implement your own signal handler.

#include<stdio.h>
#include<signal.h>
#include<unistd.h>
void sig_handler(int signum){

//Return type of the handler function should be void


printf("\nInside handler function\n");
}

int main(){
signal(SIGINT,sig_handler); // Register signal handler
for(int i=1;;i++){ //Infinite loop
printf("%d : Inside main function\n",i);
sleep(1); // Delay for 1 second
}
return 0;
}

//namei

#include <dirent.h>
#include <iostream>

using namespace std;

char* substr(char* arr, int begin,int len)


{
char* res = new char[len+1];
for(int i = 0;i < len; i++)
res[i]= *(arr + begin + 1);
res[len] = 0;
return res;
}
int main()
{
char path[100];
printf("Enter path: ");
scanf("%s",path);

DIR *dp= opendir(path);


if(dp == NULL)
{
cout<<"Error";
}
int i=0;

cout<<"Directory\t\t\tInode"<<endl;

while (path[i] != '\0')


{
if(path[i] == '/' || path[i+1] == '\0')
{
char *temp = substr(path,0,i+1);
cout<<temp<<"\t\t\t";

struct dirent *rd;


rd = readdir(dp);
cout<<rd->d_ino<<endl;
}
i++;
}
return 0;
}

//pipes

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

#include <sys/dir.h>
#include <dirent.h>

void PipeImple(char *cmd1[], char *cmd2[])


{

int pipefd[2];
pipe(pipefd);

if (fork() == 0)
{

close(1);
dup(pipefd[1]);

close(pipefd[0]);
close(pipefd[1]);

execvp(cmd1[0], cmd1);
}
else if (fork() == -1)
{

printf("Fork System call Failed!!");


_exit(0);
}
else
{

close(0);

dup(pipefd[0]);

close(pipefd[0]);
close(pipefd[1]);

execvp(cmd2[0], cmd2);
}

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


{

char *cmd1[50];
char *cmd2[50];

cmd1[0] = "cat";
cmd1[1] = "/etc/passwd";

cmd1[2] = NULL;

cmd2[0] = "grep";
cmd2[1] = "root";

cmd2[2] = NULL;

PipeImple(cmd1, cmd2);

return 0;
}

//signal call (assignment)

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>

void Exception(int signum){


printf("FPE is occured");
exit(0);
}
void parent(int signum){
printf("\n Parent : child terminated");
printf("\n Parent : Parent terminated");
}
int main()
{

int a=fork();
int c,b,x;
pid_t pid= getpid();
pid_t ppid= getppid();

if(a==0){
printf("child process is created \n");
printf("child process id : %d \n",pid);
printf("parent process id : %d \n",ppid);

signal(SIGFPE, Exception);
printf("Enter First Number: \n");
scanf("%d",&c);
printf("Enter second Number: \n");
scanf("%d",&b);
x=c/b;
printf("Result:%d \n",x);

}
else{
signal(SIGCHLD,parent);
printf("\n parent waiting for the child to finish");
pause();
}
return 0;
}

//Write a program to display the current time in the 12 hour format


#include<stdio.h>
#include <time.h>

int main(void) {
time_t t = time(NULL);
struct tm *tm = localtime(&t);
printf("%s", asctime(tm));
return 0;
}
//addition of two numbers shell script(not accurate)

#!/bin/bash
# Take input from user and calculate sum.

read -p "Enter first number: " num1


read -p "Enter second number: " num2

sum=$(( $num1 + $num2 ))

echo "Sum is: $sum"

//Write a script to compare larger integer values from a ‘n’ number of arguments
using
command line arguments

#Check if the number of arguments passed is zero


if [ "$#" = 0 ]
then
#Script exits if no
#arguments passed
echo "No arguments passed."
exit 1
fi

#Initialize maxEle with


#the first argument
maxEle=$1

#Loop that compares maxEle with the


#passed arguments and updates it
for arg in "$@"
do
if [ "$arg" -gt "$maxEle" ]
then
maxEle=$arg
fi
done
echo "Largest value among the arguments passed is: $maxEle"

//Write a script to rename current working directory with given name


rename_cwd() {
cd . || return
new_dir=${PWD%/*}/$1
mv -- "$PWD" "$new_dir" &&
cd -- "$new_dir"
}

//Write a script to sort a given number in ascending or descending order

echo enter the no of element


read n1
for (( i=0; i<$n1; i++ ))
do
echo enter `expr $i + 1` the element.
read a[$i]
done
for (( i=0; i<$n1; i++ ))
do
for (( j=`expr $i + 1`; j<$n1; j++ ))
do
if [ ${a[$i]} -gt ${a[$j]} ]
then
x=${a[$i]}
a[$i]=${a[$j]}
a[$j]=$x
fi
done
done
echo 1.Ascending 2.Descending
echo enter your choice...
read c
if [ $c = 1 ]
then
echo the ascending order is....
for (( i=0; i<$n1; i++ ))
do
echo ${a[$i]}
done
elif [ $c = 2 ]
then
echo the descending order is...
for (( i=$n1; i>0; i-- ))
do
echo ${a[`expr $i - 1`]}
done
else
echo wrong choice......
fi

//Write a shell script to display the longest and shortest user-names on the
system.
#!/bin/bash

MAX_LEN=0
MIN_LEN=100

for USER_NAME in $(cut -f1 -d: /etc/passwd)


do
if [[ ${#USER_NAME} -gt MAX_LEN ]]
then
MAX_LEN=${#USER_NAME}
MAX_LEN_USERNAME=$USER_NAME
elif [[ ${#USER_NAME} -lt MIN_LEN ]]
then
MIN_LEN=${#USER_NAME}
MIN_LEN_USERNAME=$USER_NAME
fi
done

echo “The longest user name is $MAX_LEN_USERNAME”


echo “The shortest user name is $MIN_LEN_USERNAME”

// Write a shell script to shutdown the system on receiving a ‘bye bye’ string.
Else display
greeting messages according to time. E.g.- Good morning (Till 12.00 noon).(else
part implemented)

h=$(date +"%H")
if [ $h -gt 6 -a $h -le 12 ]
then
echo good morning
elif [ $h -gt 12 -a $h -le 16 ]
then
echo good afternoon
elif [ $h -gt 16 -a $h -le 20 ]
then
echo good evening
else
echo good night
fi

// Write a shell script for reading contents of file

#!/bin/bash
read -p "Enter file name : " filename
while read -n1 character
do
echo $character
done < $filename

//Write a C program to implement ‘cp’ command using system calls.

#include <stdio.h>
#include <sys/types.h>

#define BUFSIZE 1024

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

FILE fp1, fp2;


char buf[1024];
int pos;

fp1 = open(argv[1], "r");


fp2 = open(argv[2], "w");

while((pos=read(fp1, &buf, 1024)) != 0)


{
write(fp2, &buf, 1024);
}

return 0;
}

//Write a C program to list files/subdirectories in the given directory.


#include <stdio.h>
#include <dirent.h>
int main(void){
struct dirent *files;
DIR *dir = opendir(".");
if (dir == NULL){
printf("Directory cannot be opened!" );
return 0;
}
while ((files = readdir(dir)) != NULL)
printf("%s\n", files->d_name);
closedir(dir);
return 0;
}

//Write a C program to simulate ‘grep’ command


#include<stdio.h>
#include<string.h>
void main()
{
char fn[10],pat[10],temp[200];
FILE *fp;
printf("Enter file name\n");
scanf("%s",fn);
printf("Enter pattern to be searched\n");
scanf("%s",pat);
fp=fopen(fn,"r");
while(!feof(fp))
{
fgets(temp,1000,fp);
if(strstr(temp,pat))
printf("%s",temp);
}
fclose(fp);
}

You might also like