why doesnt this code stops when i say yes? (i need to say 2 times yes) #include…
- User
why doesnt this code stops when i say yes? (i need to say 2 times yes) #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
sem_t *semaphore; int global_sum = 0; int next_line_to_read = 0; int lines_read_by_thread[NUM_THREADS] = {0}; // Array to keep track of lines read by each thread int global_sum1[100]; int global_sum2[100]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
typedef struct { FILE *fp; int start_line; int end_line; } thread_data_t;
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; } global_sum1[i]=local_sum; allthenumberstogether+=local_sum; fprintf(fp, "\n"); // printf("1 At writing: global sum at line %d: %d\n", i, global_sum1[i]); } printf("REALL Total sum: %d\n", allthenumberstogether); fclose(fp);}
void *reader_thread(void *arg) { int thread_id = (int)arg; FILE *fp = fopen("data.txt", "r"); if (!fp) { perror("Thread file opening failed"); pthread_exit(NULL); }
char line[256]; // A line will not exceed this length. while (1) { int line_to_read; pthread_mutex_lock(&mutex); if (next_line_to_read >= NUM_LINES) { pthread_mutex_unlock(&mutex); break; } line_to_read = next_line_to_read++; pthread_mutex_unlock(&mutex); // Reset file pointer for each thread to count newlines from the start. rewind(fp); int current_line = 0; while (current_line < line_to_read) { if (fgets(line, sizeof(line), fp) == NULL) { // Handle error or end of file break; } current_line++; } // Read the target line if (fgets(line, sizeof(line), fp) != NULL) { int local_sum = 0, num; char *token = strtok(line, " "); while (token != NULL) { num = atoi(token); local_sum += num; token = strtok(NULL, " "); } pthread_mutex_lock(&mutex); global_sum += local_sum; lines_read_by_thread[thread_id]++;//Increment the count for the thread printf("Thread %d read line %d, sum: %d\n", thread_id, line_to_read, local_sum); pthread_mutex_unlock(&mutex); } } fclose(fp); return NULL;}
void signal_handler(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') { // Clean-up resources sem_close(semaphore); sem_unlink("/mysemaphore"); exit(signum); }}
int main() { srand(time(NULL)); // Initialize semaphore semaphore = sem_open("/mysemaphore", O_CREAT, 0644, 0); if (semaphore == SEM_FAILED) { perror("sem_open failed"); exit(EXIT_FAILURE); } pid_t pid = fork();
if (pid < 0) { perror("fork failed"); exit(EXIT_FAILURE); } if (pid > 0) { // Parent process - writer // Install signal handlers signal(SIGINT, signal_handler); signal(SIGTERM, signal_handler); printf("starting to write\n"); generate_random_data("data.txt"); sem_post(semaphore); // Signal the child process that writing is done printf("posting semaphore\n"); wait(NULL); // Wait for the child process to finish sem_close(semaphore); sem_unlink("/mysemaphore"); printf("success parent\n"); exit(EXIT_SUCCESS); } else { // Child process - reader // Install signal handlers signal(SIGINT, signal_handler); signal(SIGTERM, signal_handler); printf("child process\n"); sem_wait(semaphore); // Wait for the parent process to finish writing printf("starting to read\n"); 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); } } // Wait for threads to finish for (int i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], NULL); } // printf 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]); } printf("Total sum: %d\n", global_sum); printf("success child\n"); exit(EXIT_SUCCESS); } return 0;}
Assistant
The issue is that the parent process (writer) is waiting for the child process (reader) to finish using the
wait(NULL)function before it exits. However, the child process is waiting for the user input in the signal handler functionsignal_handler. So, when you press 'y' to terminate the child process, it will still not terminate until all its threads have finished execution.To fix this issue, you can modify the signal handler in the child process to terminate all its threads and then exit. Here's an updated version of the signal handler function:
void signal_handler(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') { // Terminate all threads for (int i = 0; i < NUM_THREADS; i++) { pthread_cancel(threads[i]); } // Wait for threads to finish for (int i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], NULL); } // Clean-up resources sem_close(semaphore); sem_unlink("/mysemaphore"); exit(signum); } }This will terminate all threads when the user confirms the termination request, and then clean up resources and exit the child process. Note that you'll need to declare the
threadsarray as a global variable so that it's accessible from the signal handler function.Also, note that using
pthread_cancel()may leave some resources unfreed, so you might want to consider using a more graceful shutdown mechanism, such as setting a flag that the threads periodically check and exit when set.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.