Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

1)Write a program to implement ipc using named

pipe.
The entire IPC process will consist of three programs:
Program1: to create a named pipe
Program2: process that will write into the pipe (sender process)
Program3: process that will receive data from pipe (receiver process)
Program1: Creating fifo/named pipe ( 1.c )
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
int main()
{
int res;
res = mkfifo("fifo1",0777); //creates a named pipe with the name fifo1
printf("named pipe created\n");
}

Program2: Writing to a fifo/named pipe ( 2.c )


#include<unistd.h>
#include<stdio.h>
#include

\
<fcntl.h>
int main()
{
int res,n;
res=open("fifo1",O_WRONLY);
write(res,"Message",7);
printf("Sender Process %d sent the data\n",getpid());
}

Program 3: Reading from the named pipe ( 3.c )


#include<unistd.h>
#include<stdio.h>
#include<fcntl.h>
int main()
{
int res,n;
char buffer[100];
res=open("fifo1",O_RDONLY);
n=read(res,buffer,100);
printf("Reader process %d started\n",getpid());
printf("Data received by receiver %d is: %s\n",getpid(), buffer);
}

2)Write a program to implement ipc using shared memory.


Shared memory for writer process
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
using namespace std;

int main()
{
key_t key = ftok("shmfile",65);
int shmid = shmget(key,1024,0666|IPC_CREAT);
char *str = (char*) shmat(shmid,(void*)0,0);
cout<<"Write Data : ";
gets(str);
printf("Data written in memory: %s\n",str);
shmdt(str);
return 0;
}

SHARED MEMORY FOR READER PROCESS


#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
using namespace std;

int main()
{
key_t key = ftok("shmfile",65);
int shmid = shmget(key,1024,0666|IPC_CREAT);
char *str = (char*) shmat(shmid,(void*)0,0);
printf("Data read from memory: %s\n",str);
shmdt(str);
shmctl(shmid,IPC_RMID,NULL);
return 0;
}
3)Write a program to implement ipc using message queues.
MESSAGE QUEUE FOR WRITER PROCESS
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX 10
struct mesg_buffer {
long mesg_type;
char mesg_text[100];
} message;

int main()
{
key_t key;
int msgid;
key = ftok("progfile", 65);
msgid = msgget(key, 0666 | IPC_CREAT);
message.mesg_type = 1;
printf("Write Data : ");
fgets(message.mesg_text,MAX,stdin);
msgsnd(msgid, &message, sizeof(message), 0);
printf("Data send is : %s \n", message.mesg_text);
return 0;
}
MESSAGE QUEUE FOR READER PROCESS
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct mesg_buffer {
long mesg_type;
char mesg_text[100];
} message;

int main()
{
key_t key;
int msgid;
key = ftok("progfile", 65);
msgid = msgget(key, 0666 | IPC_CREAT);
msgrcv(msgid, &message, sizeof(message), 1, 0);
printf("Data Received is : %s \n", message.mesg_text);
msgctl(msgid, IPC_RMID, NULL);
return 0;
}
4)Write a program to implement ipc using unnamed pipe.
/* this example shows how unnamed pipes may be used */

#include <unistd.h>
#include <stdio.h>
#include <errno.h>

int main() {
int ret_val;
int pfd[2];
char buff[32];
char string1[]="String for pipe I/O";

ret_val = pipe(pfd); /* Create pipe */


if (ret_val != 0) { /* Test for success */
printf("Unable to create a pipe; errno=%d\n",errno);

exit(1); /* Print error message and exit */


}
if (fork() == 0) {
/* child program */
close(pfd[0]); /* close the read end */
ret_val = write(pfd[1],string1,strlen(string1)); /*Write to pipe*/
if (ret_val != strlen(string1)) {
printf("Write did not return expected value\n");
exit(2); /* Print error message and exit */
}
}
else {
/* parent program */
close(pfd[1]); /* close the write end of pipe */
ret_val = read(pfd[0],buff,strlen(string1)); /* Read from pipe */
if (ret_val != strlen(string1)) {
printf("Read did not return expected value\n");
exit(3); /* Print error message and exit */
}
printf("parent read %s from the child program\n",buff);
}
exit(0);
}

5)Write a program to write into a pipe using popen() and


pclose() functions.
#include <stdio.h>

int main() {
FILE *fp;
char buffer[100];

// Open a pipe for writing


fp = popen("wc -w", "w");

// Write a message to the pipe


fprintf(fp, "The quick brown fox jumps over the lazy dog");

// Close the pipe


pclose(fp);

// Open a pipe for reading


fp = popen("wc -w", "r");

// Read the output from the pipe


fgets(buffer, sizeof(buffer), fp);

// Print the output to the console


printf("The number of words in the input string is: %s", buffer);

// Close the pipe


pclose(fp);
return 0;
}

6)Write a program to implement ipc using pipe.


#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
int main()
{
int fd[2],n;
char buffer[100];
pid_t p;
pipe(fd); //creates a unidirectional pipe with two end fd[0] and fd[1]
p=fork();
if(p>0) //parent
{
printf("Parent Passing value to child\n");
write(fd[1],"hello\n",6); //fd[1] is the write end of the pipe
wait();
}
else // child
{
printf("Child printing received value\n");
n=read(fd[0],buffer,100); //fd[0] is the read end of the pipe
write(1,buffer,n);
}
}
7)WAP to implement the process synchronization
using mutex locks.
#include<pthread.h>
#include<stdio.h>
#include<unistd.h>
void *fun1();
void *fun2();
int shared=1; //shared variable
pthread_mutex_t l; //mutex lock
int main()
{
pthread_mutex_init(&l, NULL); //initializing mutex locks
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, fun1, NULL);
pthread_create(&thread2, NULL, fun2, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2,NULL);
printf("Final value of shared is %d\n",shared); //prints the last updated value of shared variable
}

void *fun1()
{
int x;
printf("Thread1 trying to acquire lock\n");
pthread_mutex_lock(&l); //thread one acquires the lock. Now thread 2 will not be able to
acquire the lock //until it is unlocked by thread 1
printf("Thread1 acquired lock\n");
x=shared;//thread one reads value of shared variable
printf("Thread1 reads the value of shared variable as %d\n",x);
x++; //thread one increments its value
printf("Local updation by Thread1: %d\n",x);
sleep(1); //thread one is preempted by thread 2
shared=x; //thread one updates the value of shared variable
printf("Value of shared variable updated by Thread1 is: %d\n",shared);
pthread_mutex_unlock(&l);
printf("Thread1 released the lock\n");
}

void *fun2()
{
int y;
printf("Thread2 trying to acquire lock\n");
pthread_mutex_lock(&l);
printf("Thread2 acquired lock\n");
y=shared;//thread two reads value of shared variable
printf("Thread2 reads the value as %d\n",y);
y--; //thread two increments its value
printf("Local updation by Thread2: %d\n",y);
sleep(1); //thread two is preempted by thread 1
shared=y; //thread one updates the value of shared variable
printf("Value of shared variable updated by Thread2 is: %d\n",shared);
pthread_mutex_unlock(&l);
printf("Thread2 released the lock\n");
}

8)WAP to demonstrate race condition between two


processes.
#include<pthread.h>
#include<stdio.h>
#include<unistd.h>
void *fun1();
void *fun2();
int shared=1; //shared variable
int main()
{
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, fun1, NULL);
pthread_create(&thread2, NULL, fun2, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2,NULL);
printf("Final value of shared is %d\n",shared); //prints the last updated value of shared variable
}

void *fun1()

int x;

x=shared;//thread one reads value of shared variable

printf("Thread1 reads the value of shared variable as %d\n",x);

x++; //thread one increments its value


printf("Local updation by Thread1: %d\n",x);

sleep(1); //thread one is preempted by thread 2

shared=x; //thread one updates the value of shared variable

printf("Value of shared variable updated by Thread1 is: %d\n",shared);

void *fun2()
{
int y;
y=shared;//thread two reads value of shared variable
printf("Thread2 reads the value as %d\n",y);
y--; //thread two increments its value
printf("Local updation by Thread2: %d\n",y);
sleep(1); //thread two is preempted by thread 1
shared=y; //thread one updates the value of shared variable
printf("Value of shared variable updated by Thread2 is: %d\n",shared);
}

9)Write a program to implement for process synchronization


using semaphore.
#include<pthread.h>
#include<stdio.h>
#include<semaphore.h>
#include<unistd.h>
void *fun1();
void *fun2();
int shared=1; //shared variable
sem_t s; //semaphore variable
int main()
{
sem_init(&s,0,1); //initialize semaphore variable - 1st argument is address of
variable, 2nd is number of processes sharing semaphore, 3rd argument is the initial
value of semaphore variable
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, fun1, NULL);
pthread_create(&thread2, NULL, fun2, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2,NULL);
printf("Final value of shared is %d\n",shared); //prints the last updated value of
shared variable
}
void *fun1()
{
int x;
sem_wait(&s); //executes wait operation on s
x=shared;//thread1 reads value of shared variable
printf("Thread1 reads the value as %d\n",x);
x++; //thread1 increments its value
printf("Local updation by Thread1: %d\n",x);
sleep(1); //thread1 is preempted by thread 2
shared=x; //thread one updates the value of shared variable
printf("Value of shared variable updated by Thread1 is: %d\n",shared);
sem_post(&s);
}
void *fun2()
{
int y;
sem_wait(&s);
y=shared;//thread2 reads value of shared variable
printf("Thread2 reads the value as %d\n",y);
y--; //thread2 increments its value
printf("Local updation by Thread2: %d\n",y);
sleep(1); //thread2 is preempted by thread 1
shared=y; //thread2 updates the value of shared variable
printf("Value of shared variable updated by Thread2 is: %d\n",shared);
sem_post(&s);
}
10)Write a program to implement for process
synchronization using mutex lock.
#include<pthread.h>
#include<stdio.h>
#include<unistd.h>
void *fun1();
void *fun2();
int shared=1; //shared variable
pthread_mutex_t l; //mutex lock
int main()
{
pthread_mutex_init(&l, NULL); //initializing mutex locks
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, fun1, NULL);
pthread_create(&thread2, NULL, fun2, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2,NULL);
printf("Final value of shared is %d\n",shared); //prints the last updated value of shared variable
}

void *fun1()
{
int x;
printf("Thread1 trying to acquire lock\n");
pthread_mutex_lock(&l); //thread one acquires the lock. Now thread 2 will not be able to
acquire the lock //until it is unlocked by thread 1
printf("Thread1 acquired lock\n");
x=shared;//thread one reads value of shared variable
printf("Thread1 reads the value of shared variable as %d\n",x);
x++; //thread one increments its value
printf("Local updation by Thread1: %d\n",x);
sleep(1); //thread one is preempted by thread 2
shared=x; //thread one updates the value of shared variable
printf("Value of shared variable updated by Thread1 is: %d\n",shared);
pthread_mutex_unlock(&l);
printf("Thread1 released the lock\n");
}

void *fun2()
{
int y;
printf("Thread2 trying to acquire lock\n");
pthread_mutex_lock(&l);
printf("Thread2 acquired lock\n");
y=shared;//thread two reads value of shared variable
printf("Thread2 reads the value as %d\n",y);
y--; //thread two increments its value
printf("Local updation by Thread2: %d\n",y);
sleep(1); //thread two is preempted by thread 1
shared=y; //thread one updates the value of shared variable
printf("Value of shared variable updated by Thread2 is: %d\n",shared);
pthread_mutex_unlock(&l);
printf("Thread2 released the lock\n");
}

11)WAP to read last 10 characters from a file using


system calls.
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

int main() {
int fd;
char buf[10];

// Open the file for reading


fd = open("example.txt", O_RDONLY);

// Seek to 10 characters before the end of the file


lseek(fd, -10, SEEK_END);

// Read the last 10 characters


read(fd, buf, 10);

// Close the file


close(fd);

// Print the last 10 characters


printf("Last 10 characters: %s\n", buf);
return 0;
}
12)WAP which will copy all the data from one file to another
file using system calls.

#include <stdlib.h> // For exit()

int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;

printf("Enter the filename to open for reading \n");


scanf("%s", filename);
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}

printf("Enter the filename to open for writing \n");


scanf("%s", filename);
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}

c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}

printf("\nContents copied to %s", filename);

fclose(fptr1);
fclose(fptr2);
return 0;
}

13)Write a program to implement race condition using


semaphore.
#include<pthread.h>
#include<stdio.h>
#include<semaphore.h>
#include<unistd.h>
void *fun1();
void *fun2();
int shared=1; //shared variable
sem_t s; //semaphore variable
int main()
{
sem_init(&s,0,1); //initialize semaphore variable - 1st argument is address of
variable, 2nd is number of processes sharing semaphore, 3rd argument is the initial
value of semaphore variable
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, fun1, NULL);
pthread_create(&thread2, NULL, fun2, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2,NULL);
printf("Final value of shared is %d\n",shared); //prints the last updated value of
shared variable
}

void *fun1()
{
int x;
sem_wait(&s); //executes wait operation on s
x=shared;//thread1 reads value of shared variable
printf("Thread1 reads the value as %d\n",x);
x++; //thread1 increments its value
printf("Local updation by Thread1: %d\n",x);
sleep(1); //thread1 is preempted by thread 2
shared=x; //thread one updates the value of shared variable
printf("Value of shared variable updated by Thread1 is: %d\n",shared);
sem_post(&s);
}

void *fun2()
{
int y;
sem_wait(&s);
y=shared;//thread2 reads value of shared variable
printf("Thread2 reads the value as %d\n",y);
y--; //thread2 increments its value
printf("Local updation by Thread2: %d\n",y);
sleep(1); //thread2 is preempted by thread 1
shared=y; //thread2 updates the value of shared variable
printf("Value of shared variable updated by Thread2 is: %d\n",shared);
sem_post(&s);
}

14)WAP to read last 10 characters from a file using system


calls
#include<stdio.h>
int main() {
FILE *fp;
char ch;
// Read last num characters from end
int number = 10;
long length;

fp = fopen("opengenus.txt", "r");
if (fp == NULL) {
puts("cannot open this file");
exit(1);
}
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fseek(fp, (length - number), SEEK_SET);
do {
ch = fgetc(fp);
putchar(ch);
} while (ch != EOF);
fclose(fp);
return(0);
}

15)WAP to create one parent process and one child process


also display id of both processes.
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>

int main()
{
int pid;
pid=fork();
if(pid<0)
{
printf("\n Error ");
exit(1);
}
else if(pid==0)
{
printf("\n Hello I am the child process ");
printf("\n My pid is %d ",getpid());
exit(0);
}
else
{
printf("\n Hello I am the parent process ");
printf("\n My actual pid is %d \n ",getpid());
exit(1);
}

16)WAP to create a file with some lines of content and write “hello”
into that file after 4 characters from starting using system call.

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

int main() {
int fd;
char buffer[100] = "This is some content\n";
char hello[6] = "hello";

// Create a file
fd = open("test.txt", O_CREAT | O_WRONLY, 0644);

// Write some content to the file


write(fd, buffer, strlen(buffer));

// Move the file pointer to the 5th character


lseek(fd, 4, SEEK_SET);

// Write "hello" to the file


write(fd, hello, strlen(hello));

// Close the file


close(fd);

return 0;
}

17)Write a program to create two threads. One thread prints a


welcome message while the second thread adds two numbers. Both
the numbers to be added are passed by the main process to the
thread as arguments.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

// function for thread 1


void* printMessage(void* arg) {
printf("Welcome to the program!\n");
pthread_exit(NULL);
}

// function for thread 2


void* addNumbers(void* arg) {
int* numbers = (int*) arg;
int sum = numbers[0] + numbers[1];
printf("The sum of %d and %d is %d\n", numbers[0], numbers[1], sum);
pthread_exit(NULL);
}

int main() {
pthread_t thread1, thread2;
int numbers[2] = {5, 7};

// create thread 1
pthread_create(&thread1, NULL, printMessage, NULL);

// create thread 2
pthread_create(&thread2, NULL, addNumbers, (void*) numbers);

// wait for threads to finish


pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}

18)WAP to create three threads. One thread prints a welcome


message while the second thread do addition of two numbers Third
thread print the ending message

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

// function for thread 1


void* printMessage(void* arg) {
printf("Welcome to the program!\n");
pthread_exit(NULL);
}

// function for thread 2


void* addNumbers(void* arg) {
int* numbers = (int*) arg;
int sum = numbers[0] + numbers[1];
printf("The sum of %d and %d is %d\n", numbers[0], numbers[1], sum);
pthread_exit(NULL);
}

// function for thread 3


void* printEndMessage(void* arg) {
printf("Thanks for using the program!\n");
pthread_exit(NULL);
}

int main() {
pthread_t thread1, thread2, thread3;
int numbers[2] = {5, 7};

// create thread 1
pthread_create(&thread1, NULL, printMessage, NULL);

// create thread 2
pthread_create(&thread2, NULL, addNumbers, (void*) numbers);

// create thread 3
pthread_create(&thread3, NULL, printEndMessage, NULL);

// wait for threads to finish


pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join(thread3, NULL);

return 0;
}
19)Write a program to create a child process. The parent
process prints 20-29 and child process prints 0-8 Also both
the process prints a common message
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main() {
int pid = fork();

if (pid == -1) {
printf("Failed to create child process\n");
return 1;
}

if (pid == 0) { // child process


printf("Child process started\n");
for (int i = 0; i < 9; i++) {
printf("%d ", i);
}
printf("\nChild process finished\n");
} else { // parent process
printf("Parent process started\n");
for (int i = 20; i < 30; i++) {
printf("%d ", i);
}
printf("\nParent process finished\n");
}
return 0;
}
20)Write a program to create a thread. The main thread
should print the numbers from 20 to 25 and the user-created
thread should print first five prime numbers
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

// function for user-defined thread


void* printPrimes(void* arg) {
int count = 0;
int num = 2;

printf("First five prime numbers: ");


while (count < 5) {
int isPrime = 1;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = 0;
break;
}
}
if (isPrime) {
printf("%d ", num);
count++;
}
num++;
}
printf("\n");
pthread_exit(NULL);
}

int main() {
pthread_t thread;

// create user-defined thread


pthread_create(&thread, NULL, printPrimes, NULL);

// print numbers from 20 to 25


printf("Numbers from 20 to 25: ");
for (int i = 20; i <= 25; i++) {
printf("%d ", i);
}
printf("\n");

// wait for user-defined thread to finish


pthread_join(thread, NULL);

return 0;
}

21)WAP to create the following hierarchy and verify the relationship using
getpid() and getppid().P1->P2->P3

22)WAP to create two threads. One will print the numbers from 1 to 10 and
the other thread will find whether a number entered by the user is even or
odd
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *print_numbers(void *args) {


int i;

printf("Printing numbers 1 to 10:\n");


for (i = 1; i <= 10; i++) {
printf("%d\n", i);
}

pthread_exit(NULL);
}

void *check_even_odd(void *args) {


int num;

printf("Enter a number to check if it is even or odd: ");


scanf("%d", &num);

if (num % 2 == 0) {
printf("%d is even\n", num);
} else {
printf("%d is odd\n", num);
}

pthread_exit(NULL);
}

int main() {
pthread_t tid1, tid2;
int ret1, ret2;

ret1 = pthread_create(&tid1, NULL, &print_numbers, NULL);


if (ret1 != 0) {
printf("Failed to create thread 1\n");
return 1;
}

ret2 = pthread_create(&tid2, NULL, &check_even_odd, NULL);


if (ret2 != 0) {
printf("Failed to create thread 2\n");
return 1;
}

pthread_join(tid1, NULL);
pthread_join(tid2, NULL);

return 0;
}
23)Write a program to create following hierarchy and verify the
relationship between the processes. Where process P1 has 2
children P2 and P3.

#include <stdio.h>
#include <unistd.h>

int main() {
pid_t pid1, pid2;

pid1 = fork();
if (pid1 == -1) {
printf("Failed to create P2\n");
return 1;
} else if (pid1 == 0) {
printf("I am P2 with pid %d and my parent is P1 with pid %d\n", getpid(), getppid());
return 0;
}

pid2 = fork();
if (pid2 == -1) {
printf("Failed to create P3\n");
return 1;
} else if (pid2 == 0) {
printf("I am P3 with pid %d and my parent is P1 with pid %d\n", getpid(), getppid());
return 0;
}

printf("I am P1 with pid %d\n", getpid());

return 0;
}

Perform the following operations using Linux commands

a Create two files, write contents into them and merge them into
one

b. Create a directory D1, create a file F1 and directory 02 into the


directory D1 and delete the directory DT

c. Change the permission of the file to user read, write and execute,
group read and execute, others read

You might also like