Complete Programs — Shell & System Programming Lab
Contains: 10 Shell scripts (with aim, algorithm, program, sample output) and 10 System programming C programs (with
aim, algorithm, program, sample output).
Generated for lab practice — Jay A
1. Hello World (Shell)
Aim: Print Hello World using a bash script.
Algorithm: 1. Start script. 2. Use echo to print text. 3. End.
Program:
#!/bin/bash
# Hello World
echo "Hello World"
Sample Output:
Hello World
2. For Loop (1..5)
Aim: Print numbers 1 to 5 using a for loop.
Algorithm: 1. Use for loop with sequence. 2. Echo each number.
Program:
#!/bin/bash
for i in {1..5}
do
echo "Number: $i"
done
Sample Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
3. If-Else (Check >10)
Aim: Check if a command line argument is greater than 10.
Algorithm: 1. Read $1. 2. Compare with 10 using -gt. 3. Print result.
Program:
#!/bin/bash
if [ $# -eq 0 ]
then
echo "Usage: $0 number"
exit 1
fi
if [ $1 -gt 10 ]
then
echo "Greater than 10"
else
echo "Less or equal to 10"
fi
Sample Output:
(when run with 15) => Greater than 10
4. Factorial (Shell)
Aim: Compute factorial of a positive integer.
Algorithm: 1. Read n from argument. 2. Loop from 1 to n and multiply.
Program:
#!/bin/bash
if [ $# -eq 0 ]
then
echo "Usage: $0 n"
exit 1
fi
n=$1
fact=1
for (( i=1; i<=n; i++ ))
do
fact=$((fact * i))
done
echo $fact
Sample Output:
(for n=5) => 120
5. Count Lines Words Characters
Aim: Count lines, words and characters in a file using wc.
Algorithm: 1. Accept filename. 2. Use wc to display counts.
Program:
#!/bin/bash
if [ $# -eq 0 ]
then
echo "Usage: $0 filename"
exit 1
fi
wc "$1"
Sample Output:
Example: 10 50 300 filename
6. Menu-driven Calculator
Aim: Simple calculator using case statement.
Algorithm: 1. Show menu. 2. Read choice and operands. 3. Perform operation.
Program:
#!/bin/bash
while true; do
echo "1) Add 2) Sub 3) Mul 4) Div 5) Exit"
read -p "Choice: " ch
if [ "$ch" -eq 5 ]; then break; fi
read -p "Enter a: " a
read -p "Enter b: " b
case $ch in
1) echo "Result: $((a+b))";;
2) echo "Result: $((a-b))";;
3) echo "Result: $((a*b))";;
4) echo "Result: $((a/b))";;
*) echo "Invalid";;
esac
done
Sample Output:
(interactive — shows results)
7. String Reverse (Shell)
Aim: Reverse a string using parameter expansion and rev.
Algorithm: 1. Read string. 2. Use rev or loop to reverse. 3. Print.
Program:
#!/bin/bash
read -p "Enter string: " s
# Using rev command
echo "$s" | rev
Sample Output:
(input: hello) => olleh
8. Search Pattern with grep & awk
Aim: Search for pattern and print matching lines with line numbers.
Algorithm: 1. Accept pattern and file. 2. Use grep -n to list matches.
Program:
#!/bin/bash
if [ $# -lt 2 ]; then
echo "Usage: $0 pattern filename"
exit 1
fi
pattern=$1
file=$2
grep -n "$pattern" "$file"
Sample Output:
(example) => 3:This line contains pattern
9. Backup Script (tar)
Aim: Create a timestamped [Link] backup of a directory.
Algorithm: 1. Read directory. 2. Create [Link] with date in name.
Program:
#!/bin/bash
if [ $# -eq 0 ]; then
echo "Usage: $0 directory"
exit 1
fi
dir=$1
now=$(date +"%Y%m%d_%H%M%S")
tar -czf "${dir}_backup_${now}.[Link]" "$dir"
echo "Backup created"
Sample Output:
Backup created (file [Link])
10. Cron Job Example ([Link])
Aim: Show cron entry to run backup daily at 2 AM.
Algorithm: 1. Create script [Link]. 2. Add crontab entry.
Program:
# [Link] (same as previous script)
# Crontab entry to edit with crontab -e:
# 0 2 * * * /home/user/[Link] /home/user/data >> /home/user/[Link] 2>&1
Sample Output:
Runs daily at 2:00 AM
1. fork() Example
Aim: Create child process using fork() and demonstrate both processes.
Algorithm: 1. Call fork(). 2. Check return value. 3. Parent and child print messages.
Program (C):
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main() {
pid_t pid = fork();
if (pid < 0) {
perror("fork failed");
return 1;
} else if (pid == 0) {
// Child
printf("Child process: pid=%d, ppid=%d\n", getpid(), getppid());
} else {
// Parent
printf("Parent process: child pid=%d, pid=%d\n", pid, getpid());
}
return 0;
}
Sample Output:
Parent process: child pid=12345, pid=12344
Child process: pid=12345, ppid=12344
2. exec() Example (execl)
Aim: Replace current process with ls using execl.
Algorithm: 1. Call execl with /bin/ls. 2. If returns, print error.
Program (C):
#include <stdio.h>
#include <unistd.h>
int main() {
execl("/bin/ls", "ls", "-l", (char *)NULL);
perror("execl failed");
return 1;
}
Sample Output:
(Lists directory contents as ls -l)
3. Pipe between parent and child
Aim: Use pipe() to send data from parent to child (or vice versa).
Algorithm: 1. Create pipe. 2. fork(). 3. Parent writes, child reads.
Program (C):
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main() {
int fd[2];
pipe(fd);
pid_t pid = fork();
if (pid == 0) {
// child reads
close(fd[1]);
char buf[100];
int n = read(fd[0], buf, sizeof(buf));
buf[n] = '\0';
printf("Child received: %s\n", buf);
} else {
// parent writes
close(fd[0]);
char *msg = "Hello from parent";
write(fd[1], msg, strlen(msg));
}
return 0;
}
Sample Output:
Child received: Hello from parent
4. Signal Handling (SIGINT)
Aim: Catch Ctrl+C (SIGINT) and handle gracefully.
Algorithm: 1. Register signal handler. 2. In handler, print message. 3. Continue or exit.
Program (C):
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
void handler(int sig) {
printf("Caught signal %d\n", sig);
}
int main() {
signal(SIGINT, handler);
while(1) {
printf("Running... press Ctrl+C\n");
sleep(3);
}
return 0;
}
Sample Output:
Running... press Ctrl+C
(Ctrl+C pressed) => Caught signal 2
5. File I/O using open, read, write
Aim: Copy a file using low-level system calls.
Algorithm: 1. Open source and destination. 2. Read chunks and write to dest. 3. Close files.
Program (C):
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc < 3) { printf("Usage: %s src dst\n", argv[0]); return 1; }
int in = open(argv[1], O_RDONLY);
int out = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644);
char buf[1024];
ssize_t n;
while ((n = read(in, buf, sizeof(buf))) > 0) {
write(out, buf, n);
}
close(in); close(out);
return 0;
}
Sample Output:
Creates a copy of source file as destination file
6. Shared Memory (shmget, shmat)
Aim: Create shared memory segment and write/read from it.
Algorithm: 1. shmget to allocate. 2. shmat to attach. 3. Write and read, then shmctl to remove.
Program (C):
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <string.h>
int main() {
int id = shmget(0x1234, 1024, 0666 | IPC_CREAT);
char *p = (char *)shmat(id, NULL, 0);
strcpy(p, "Hello SHM");
printf("Wrote to SHM: %s\n", p);
shmdt(p);
// shmctl(id, IPC_RMID, NULL); // uncomment to remove
return 0;
}
Sample Output:
Wrote to SHM: Hello SHM
7. Message Queue (msgget, msgsnd, msgrcv)
Aim: Send and receive a message using System V message queue.
Algorithm: 1. msgget to create queue. 2. msgsnd to send. 3. msgrcv to receive.
Program (C):
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
struct msgbuf { long mtype; char mtext[100]; };
int main() {
int id = msgget(0x5678, 0666 | IPC_CREAT);
struct msgbuf mb;
[Link] = 1;
strcpy([Link], "Hello MQ");
msgsnd(id, &mb, sizeof([Link]), 0);
printf("Message sent\n");
// msgrcv example omitted for brevity
return 0;
}
Sample Output:
Message sent
8. Semaphore (POSIX sem_init example)
Aim: Demonstrate simple semaphore usage between threads/processes.
Algorithm: 1. Initialize semaphore. 2. sem_wait before critical section. 3. sem_post after.
Program (C):
#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>
sem_t sem;
void* worker(void* arg) {
sem_wait(&sem);
printf("In critical section\n");
sem_post(&sem);
return NULL;
}
int main() {
pthread_t t1, t2;
sem_init(&sem, 0, 1);
pthread_create(&t1, NULL, worker, NULL);
pthread_create(&t2, NULL, worker, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
sem_destroy(&sem);
return 0;
}
Sample Output:
In critical section
In critical section
9. Threading with pthreads
Aim: Create threads and join them using pthreads.
Algorithm: 1. Create multiple threads. 2. Each prints a message. 3. Join threads.
Program (C):
#include <pthread.h>
#include <stdio.h>
void* routine(void* arg) {
printf("Thread says hello\n");
return NULL;
}
int main() {
pthread_t t1, t2;
pthread_create(&t1, NULL, routine, NULL);
pthread_create(&t2, NULL, routine, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}
Sample Output:
Thread says hello
Thread says hello
10. Socket (simple TCP client)
Aim: Create a simple TCP client that connects to a server and sends a message.
Algorithm: 1. Create socket. 2. connect to server. 3. send and receive data. 4. close.
Program (C):
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
int main() {
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
inet_pton(AF_INET, "[Link]", &addr.sin_addr);
connect(sock, (struct sockaddr*)&addr, sizeof(addr));
char *msg = "Hello server";
send(sock, msg, strlen(msg), 0);
close(sock);
return 0;
}
Sample Output:
Sends 'Hello server' to listening server on localhost:8080