[go: up one dir, main page]

0% found this document useful (0 votes)
28 views11 pages

Experiments For Practice

contains experiments

Uploaded by

menotnandan6969
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views11 pages

Experiments For Practice

contains experiments

Uploaded by

menotnandan6969
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Programs for Practice

1. program showcases how to create child processes, wait for their completion, and
execute different commands within these processes using system calls like
fork (), exec () and wait ().

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
pid_t pid;
int status;

printf("Parent process (PID: %d)\n", getpid());

// Fork a child process


pid = fork();

if (pid < 0) {
// Fork failed
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// Child process
printf("Child process (PID: %d), Parent PID: %d\n", getpid(), getppid());

// Execute 'ls' command in the child process


char *args[] = {"ls", "-l", NULL};
execvp(args[0], args);

// execvp() will replace the child process image if successful,


// so the following code will only run if execvp() fails
perror("execvp");
exit(EXIT_FAILURE);
} else {
// Parent process
printf("Parent process waiting for child (PID: %d) to complete...\n", pid);

// Wait for the child process to complete


waitpid(pid, &status, 0);

if (WIFEXITED(status)) {
printf("Child process exited with status: %d\n", WEXITSTATUS(status));
} else {
printf("Child process terminated abnormally\n");
}
}
return 0;
}

2. C program that creates a thread using NULL attributes

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

void* thread_function(void* arg) {


// This function will be executed by the new thread
printf("This is a new thread running!\n");
pthread_exit(NULL); // Exit the thread
}

int main() {
pthread_t thread_id; // Thread ID variable

// Create a new thread with default attributes (NULL)


int result = pthread_create(&thread_id, NULL, thread_function, NULL);

if (result != 0) {
perror("Thread creation failed"); // Print an error message if thread creation fails
exit(EXIT_FAILURE);
}

printf("Main thread: Created a new thread with ID %lu\n", thread_id);

// Wait for the created thread to finish executing


pthread_join(thread_id, NULL);

printf("Main thread: New thread has terminated\n");

return 0;
}

3. Program that demonstrates a multithreaded prime number checker using


Pthreads in C.

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

#define NUM_THREADS 4

// Structure to pass arguments to thread function


struct ThreadData {
int start;
int end;
};

// Function to check if a number is prime


int is_prime(int num) {
if (num <= 1) return 0; // 0 and 1 are not prime numbers
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return 0;
}
return 1;
}

// Thread function to check prime numbers in a range


void *check_prime_range(void *arg) {
struct ThreadData *data = (struct ThreadData *)arg;
int start = data->start;
int end = data->end;

printf("Checking prime numbers in range %d to %d\n", start, end);

for (int i = start; i <= end; i++) {


if (is_prime(i)) {
printf("%d is prime\n", i);
}
}

pthread_exit(NULL);
}

int main() {
pthread_t tid[NUM_THREADS];
struct ThreadData thread_data[NUM_THREADS];
int range_start = 1;
int range_end = 100;
int range_size = (range_end - range_start + 1) / NUM_THREADS;
int remainder = (range_end - range_start + 1) % NUM_THREADS;

// Create threads to check prime numbers in different ranges


for (int i = 0; i < NUM_THREADS; i++) {
int start = range_start + i * range_size;
int end = start + range_size - 1;
if (i == NUM_THREADS - 1) {
end += remainder; // Adjust the last thread's range
}
thread_data[i].start = start;
thread_data[i].end = end;
pthread_create(&tid[i], NULL, check_prime_range, (void *)&thread_data[i]);
}
// Wait for all threads to finish
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(tid[i], NULL);
}

return 0;
}

4. Program for multiple threads which concurrently compute and update a shared
variable using mutex locks for synchronization

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

#define NUM_THREADS 4
#define ITERATIONS 1000000

int shared_variable = 0;
pthread_mutex_t mutex;

void *thread_function(void *arg) {


int tid = *((int *)arg);
for (int i = 0; i < ITERATIONS; i++) {
pthread_mutex_lock(&mutex);
shared_variable++;
pthread_mutex_unlock(&mutex);
}
printf("Thread %d finished. Shared variable value: %d\n", tid, shared_variable);
pthread_exit(NULL);
}

int main() {
pthread_t threads[NUM_THREADS];
int thread_ids[NUM_THREADS];

pthread_mutex_init(&mutex, NULL);

// Create threads
for (int i = 0; i < NUM_THREADS; i++) {
thread_ids[i] = i;
if (pthread_create(&threads[i], NULL, thread_function, &thread_ids[i]) != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
}

// Wait for threads to finish


for (int i = 0; i < NUM_THREADS; i++) {
if (pthread_join(threads[i], NULL) != 0) {
perror("pthread_join");
exit(EXIT_FAILURE);
}
}

pthread_mutex_destroy(&mutex);

printf("All threads have finished execution. Final value of shared variable: %d\n",
shared_variable);

return 0;
}

5. Process synchronization based on semaphores

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

#define NUM_THREADS 2

int shared_resource = 0;
sem_t semaphore;

void* thread_function(void* arg) {


int thread_id = *((int*)arg);

// Acquire semaphore
sem_wait(&semaphore);

// Critical section
printf("Thread %d: Entering critical section\n", thread_id);
shared_resource++;
printf("Thread %d: Shared resource updated to %d\n", thread_id, shared_resource);
printf("Thread %d: Exiting critical section\n", thread_id);

// Release semaphore
sem_post(&semaphore);

pthread_exit(NULL);
}

int main() {
pthread_t threads[NUM_THREADS];
int thread_ids[NUM_THREADS];
// Initialize semaphore
sem_init(&semaphore, 0, 1);

// Create threads
for (int i = 0; i < NUM_THREADS; i++) {
thread_ids[i] = i;
pthread_create(&threads[i], NULL, thread_function, (void*)&thread_ids[i]);
}

// Join threads
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}

// Destroy semaphore
sem_destroy(&semaphore);

return 0;
}

6. Process Synchronization based on mutex lock

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

#define NUM_THREADS 2

int shared_resource = 0;
pthread_mutex_t mutex;

void* thread_function(void* arg) {


int thread_id = *((int*)arg);

// Lock mutex
pthread_mutex_lock(&mutex);

// Critical section
printf("Thread %d: Entering critical section\n", thread_id);
shared_resource++;
printf("Thread %d: Shared resource updated to %d\n", thread_id, shared_resource);
printf("Thread %d: Exiting critical section\n", thread_id);

// Unlock mutex
pthread_mutex_unlock(&mutex);

pthread_exit(NULL);
}
int main() {
pthread_t threads[NUM_THREADS];
int thread_ids[NUM_THREADS];

// Initialize mutex
pthread_mutex_init(&mutex, NULL);

// Create threads
for (int i = 0; i < NUM_THREADS; i++) {
thread_ids[i] = i;
pthread_create(&threads[i], NULL, thread_function, (void*)&thread_ids[i]);
}

// Join threads
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}

// Destroy mutex
pthread_mutex_destroy(&mutex);

return 0;
}

7. Program based on Race condition

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

#define NUM_THREADS 4
#define NUM_INCREMENTS 1000000

int shared_variable = 0;

void* increment_function(void* arg) {


for (int i = 0; i < NUM_INCREMENTS; i++) {
shared_variable++; // Increment the shared variable
}
pthread_exit(NULL);
}

int main() {
pthread_t threads[NUM_THREADS];
int rc;
long t;

// Create threads
for (t = 0; t < NUM_THREADS; t++) {
rc = pthread_create(&threads[t], NULL, increment_function, NULL);
if (rc) {
fprintf(stderr, "Error: pthread_create() failed\n");
exit(EXIT_FAILURE);
}
}

// Wait for all threads to complete


for (t = 0; t < NUM_THREADS; t++) {
pthread_join(threads[t], NULL);
}

// After all threads have finished, print the final value of the shared variable
printf("Final value of shared_variable: %d\n", shared_variable);

return 0;
}

8. Program using pipe function

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

int main() {
int fd[2];
pid_t pid;
char message[] = "Hello, pipe!";

if (pipe(fd) == -1) {
perror("pipe");
return 1;
}

pid = fork();

if (pid == 0) {
// Child process
close(fd[0]); // Close unused read end
write(fd[1], message, sizeof(message));
close(fd[1]);
} else if (pid > 0) {
// Parent process
close(fd[1]); // Close unused write end
char buffer[100];
read(fd[0], buffer, sizeof(buffer));
printf("Received message: %s\n", buffer);
close(fd[0]);
} else {
perror("fork");
return 1;
}

return 0;
}

9. Program using shared memory

#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define SHM_SIZE 1024

int main() {
key_t key = 1234;
int shmid;
char *shm_ptr;

shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666);


if (shmid == -1) {
perror("shmget");
return 1;
}

shm_ptr = shmat(shmid, NULL, 0);


if (shm_ptr == (char *) -1) {
perror("shmat");
return 1;
}

sprintf(shm_ptr, "Hello, shared memory!");

printf("Data written to shared memory: %s\n", shm_ptr);

shmdt(shm_ptr);

return 0;
}

10. Program based on Message queue

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define MSG_SIZE 128

struct message {
long msg_type;
char msg_text[MSG_SIZE];
};

int main() {
key_t key = 1234;
int msqid;
struct message msg;

msqid = msgget(key, IPC_CREAT | 0666);


if (msqid == -1) {
perror("msgget");
return 1;
}

msg.msg_type = 1;
sprintf(msg.msg_text, "Hello, message queue!");

if (msgsnd(msqid, (void *) &msg, MSG_SIZE, IPC_NOWAIT) == -1) {


perror("msgsnd");
return 1;
}

printf("Message sent: %s\n", msg.msg_text);

return 0;
}
11. Program based on socket

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>

#define PORT 8080

int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
char message[] = "Hello, socket!";

// Creating socket file descriptor


if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}

address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);

// Binding socket to the port


if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}

// Listening for connections


if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}

if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) <


0) {
perror("accept");
exit(EXIT_FAILURE);
}

// Sending message
send(new_socket, message, strlen(message), 0);
printf("Message sent: %s\n", message);

return 0;
}

You might also like