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>
#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
char lines[NUM_LINES][MAX_LINE_LENGTH];
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");
}
// 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
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);
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);
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));
// Initialize semaphore
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); // 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;
}