in this program make the file to be processed by the threads also dont copy the lines in an array calculate them directly using lseek:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <semaphore.h>
#include <signal.h>
#include <time.h>
#include <string.h>
pid_t pid;
sem_t *semaphore;
int global_sum = 0;
int lines_read_by_thread[NUM_THREADS] = {0}; // Array to keep track of lines read by each thread
char lines[NUM_LINES][MAX_LINE_LENGTH];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void generate_random_data(const char *filename) {
code
FILE *fp = fopen(filename, "w");
if (!fp) {
perror("File opening failed");
exit(EXIT_FAILURE);
}
int allthenumberstogether=0;
for (int i = 0; i < NUM_LINES; i++) {
int local_sum = 0;
for (int j = 0; j < NUMBERS_PER_LINE; j++) {
int randomnumber = rand() % 101;
fprintf(fp, "%d ", randomnumber);
local_sum += randomnumber;
}
allthenumberstogether+=local_sum;
fprintf(fp, "\n");
}
// printf("REAL Total sum: %d\n", allthenumberstogether);
fclose(fp);
printf("writing done\n");
}
void *reader_thread(void *arg) {
int thread_id = (int)arg;
char line_copy[MAX_LINE_LENGTH]; // Local buffer for tokenizing
code
for (int i = thread_id; i < NUM_LINES; i += NUM_THREADS) {
strncpy(line_copy, lines[i], MAX_LINE_LENGTH);
line_copy[MAX_LINE_LENGTH - 1] = '\0';
int local_sum = 0, num;
char *saveptr; // For strtok_r's state
char *token = strtok_r(line_copy, " ", &saveptr);
while (token != NULL) {
num = atoi(token);
local_sum += num;
token = strtok_r(NULL, " ", &saveptr);
}
pthread_mutex_lock(&mutex);
global_sum += local_sum;
lines_read_by_thread[thread_id]++;
pthread_mutex_unlock(&mutex);
}
return NULL;
}
void signal_handlerparent(int signum) {
char response;
printf("\nReceived signal %d. Do you really want to terminate (y/n)? ", signum);
scanf(" %c", &response);
code
if (response == 'y' || response == 'Y') {
printf("\nThe parent and the child process are terminating\n");
//kill the child process
kill(pid, SIGKILL);
// Clean-up resources
sem_close(semaphore);
sem_unlink("it2022007");
exit(signum);
}
}
void signal_handlerchild(int signum) {
char response;
printf("\nReceived signal %d. Do you really want to terminate (y/n)? ", signum);
scanf(" %c", &response);
code
if (response == 'y' || response == 'Y') {
printf("\nThe child process is terminating\n");
exit(signum);
}
}
void ignore_signals(int signum) {
printf("Ignoring signal %d\n", signum);
}
if (pid < 0) {
perror("fork failed");
exit(EXIT_FAILURE);
}
if (pid > 0) { // Parent process - writer
signal(SIGCHLD, SIG_IGN); // Ignore SIGCHLD to avoid zombie processes
signal(SIGINT, signal_handlerparent);
signal(SIGTERM, signal_handlerparent);
printf("starting to write\n");
generate_random_data("data.txt");
signal(SIGINT, ignore_signals);
signal(SIGTERM, ignore_signals);
sem_post(semaphore); // Signal the child process that writing is done
wait(NULL); // Wait for the child process to finish
sem_close(semaphore);
sem_unlink("it2022007");
exit(EXIT_SUCCESS);
} else { // Child process - reader
signal(SIGINT, ignore_signals);
signal(SIGTERM, ignore_signals);
sem_wait(semaphore); // Wait for the parent process to finish writing
signal(SIGINT, signal_handlerchild);
signal(SIGTERM, signal_handlerchild);
printf("starting to read\n");
// Read the file into memory
FILE *fp = fopen("data.txt", "r");
if (!fp) {
perror("Unable to open file");
exit(EXIT_FAILURE);
}
int line_count = 0;
while (fgets(lines[line_count], MAX_LINE_LENGTH, fp) && line_count < NUM_LINES) {
line_count++;
}
fclose(fp);
pthread_t threads[NUM_THREADS];
int thread_ids[NUM_THREADS];
// Create threads
for (int i = 0; i < NUM_THREADS; i++) {
thread_ids[i] = i;
if (pthread_create(&threads[i], NULL, reader_thread, (void *) &thread_ids[i]) != 0) {
perror("Failed to create thread");
exit(EXIT_FAILURE);
}
}
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
printf("reading done\n");
// print lines read by each thread
for (int i = 0; i < NUM_THREADS; i++) {
printf("Thread %d read %d lines\n", i, lines_read_by_thread[i]);
}
// print total sum
printf("Total sum: %d\n", global_sum);
exit(EXIT_SUCCESS);
}
return 0;
}
Assistant
To modify the program so that the file is processed by the threads without copying the lines into an array and instead calculating them directly using lseek, you will need to change the approach to reading the file. Here's an updated version of the program with the necessary modifications:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <semaphore.h>
#include <signal.h>
#include <time.h>
#include <string.h>
#define NUM_THREADS 4
#define NUM_LINES 100
#define NUMBERS_PER_LINE 50
#define MAX_LINE_LENGTH 256
pid_t pid;
sem_t *semaphore;
int global_sum = 0;
int lines_read_by_thread[NUM_THREADS] = {0}; // Array to keep track of lines read by each thread
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void generate_random_data(const char *filename) {
FILE *fp = fopen(filename, "w");
if (!fp) {
perror("File opening failed");
exit(EXIT_FAILURE);
}
int allthenumberstogether = 0;
for (int i = 0; i < NUM_LINES; i++) {
int local_sum = 0;
for (int j = 0; j < NUMBERS_PER_LINE; j++) {
int randomnumber = rand() % 101;
fprintf(fp, "%d ", randomnumber);
local_sum += randomnumber;
}
allthenumberstogether += local_sum;
fprintf(fp, "\n");
}
fclose(fp);
printf("Writing done\n");
}
void *reader_thread(void *arg) {
int thread_id = *(int *)arg;
int fd = open("data.txt", O_RDONLY);
if (fd < 0) {
perror("Error opening file");
exit(EXIT_FAILURE);
}
int local_sum = 0;
char buffer[MAX_LINE_LENGTH];
off_t offset = thread_id * (NUM_LINES / NUM_THREADS) * (MAX_LINE_LENGTH + 1);
if (lseek(fd, offset, SEEK_SET) < 0) {
perror("Error seeking file");
exit(EXIT_FAILURE);
}
for (int i = 0; i < NUM_LINES / NUM_THREADS; i++) {
if (read(fd, buffer, MAX_LINE_LENGTH) <= 0) {
perror("Error reading file");
exit(EXIT_FAILURE);
}
char *saveptr;
char *token = strtok_r(buffer, " ", &saveptr);
while (token != NULL) {
int num = atoi(token);
local_sum += num;
token = strtok_r(NULL, " ", &saveptr);
}
}
close(fd);
pthread_mutex_lock(&mutex);
global_sum += local_sum;
lines_read_by_thread[thread_id] += NUM_LINES / NUM_THREADS;
pthread_mutex_unlock(&mutex);
return NULL;
}
void signal_handlerparent(int signum) {
char response;
printf("\nReceived signal %d. Do you really want to terminate (y/n)? ", signum);
scanf(" %c", &response);
if (response == 'y' || response == 'Y') {
printf("\nThe parent and the child process are terminating\n");
kill(pid, SIGKILL);
sem_close(semaphore);
sem_unlink("it2022007");
exit(signum);
}
}
void signal_handlerchild(int signum) {
char response;
printf("\nReceived signal %d. Do you really want to terminate (y/n)? ", signum);
scanf(" %c", &response);
if (response == 'y' || response == 'Y') {
printf("\nThe child process is terminating\n");
exit(signum);
}
}
void ignore_signals(int signum) {
printf("Ignoring signal %d\n", signum);
}
int main() {
srand(time(NULL));
semaphore = sem_open("it2022007", O_CREAT, 0644, 0);
if (semaphore == SEM_FAILED) {
perror("sem_open failed");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid < 0) {
perror("fork failed");
exit(EXIT_FAILURE);
}
if (pid > 0) { // Parent process - writer
signal(SIGCHLD, SIG_IGN);
signal(SIGINT, signal_handlerparent);
signal(SIGTERM, signal_handlerparent);
printf("Starting to write\n");
generate_random_data("data.txt");
signal(SIGINT, ignore_signals);
signal(SIGTERM, ignore_signals);
sem_post(semaphore);
wait(NULL);
sem_close(semaphore);
sem_unlink("it2022007");
exit(EXIT_SUCCESS);
} else { // Child process - reader
signal(SIGINT, ignore_signals);
signal(SIGTERM, ignore_signals);
sem_wait(semaphore);
signal(SIGINT, signal_handlerchild);
signal(SIGTERM, signal_handlerchild);
printf("Starting to read\n");
pthread_t threads[NUM_THREADS];
int thread_ids[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
thread_ids[i] = i;
if (pthread_create(&threads[i], NULL, reader_thread, (void *)&thread_ids[i]) != 0) {
perror("Failed to create thread");
exit(EXIT_FAILURE);
}
}
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
printf("Reading done\n");
for (int i = 0; i < NUM_THREADS; i++) {
printf("Thread %d read %d lines\n", i, lines_read_by_thread[i]);
}
printf("Total sum: %d\n", global_sum);
exit(EXIT_SUCCESS);
}
return 0;
}
In this modified version of the program:
The reader_thread function now opens the file in read-only mode and uses lseek to position the file pointer for each thread to read a specific portion of the file without copying the lines into an array.
The file reading and processing are done directly within each thread, calculating the sum of numbers on the fly without storing the lines in memory.
The generate_random_data function remains the same for writing random data to the file.
The rest of the program structure and signal handling mechanisms remain unchanged.