OS Code

mail@pastecode.io avatar
unknown
c_cpp
a year ago
2.3 kB
3
Indexable
Never
// We open a file using a thread
// the thread will write something into the file
// Then it goes to sleep while the MAIN writes something to the file
// Then we read everything written to the file using the thread
 
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <fcntl.h>
#include <string.h>
 
void* runner (void* arg){
    // as we want to append using the main thread
    int fd = open("test.txt", O_RDWR | O_CREAT | O_APPEND);
    if(fd == -1){
        perror("Couldnt create a file");
        return 2;
    }
    printf("{RUNNER} The file has been created\n");
 
    // writing to the file
    char* sentence2 = "Test from runner \n";
    printf("Wrote %s\n", sentence2);
    write(fd, sentence2, strlen(sentence2));
 
    printf("{RUNNER} Written to the test file \n");
    printf("{RUNNER} Going to sleep for the MAIN thread to come into action\n");
 
    // now we go to sleep for the MAIN thread to append more content to the test file
    sleep(10);
 
    printf("{RUNNER} is awake, proceeding to the read the data from the file\n");
    char read_buffer[1000];
    read(fd, &read_buffer,sizeof(read_buffer)); // plus one for the lseek
 
    printf("{RUNNER} Reading is succesful\n");
    printf("{RUNNER} Data read : %s\n", read_buffer);
    pthread_exit(0);
}
 
int main(int argc, char *argv[]){

    pthread_t thread1;
    
    // creating the thread
    if(pthread_create(&thread1, NULL, &runner, NULL) != 0){
        perror("Couldnt create thread");
        return 1;
    };

    printf("{MAIN} Runner is created. MAIN is going to sleep for the runner to write to the test file\n");
    sleep(5); // while the thread finishes writing to the file it creates
    
    printf("{MAIN} has now woken up, appending more data to the test file\n");
    int fd = open("test.txt", O_RDWR | O_APPEND);
    if(fd == -1){
        perror("Couldnt create a file");
        return 2;
    }
    lseek(fd, 1, SEEK_END);
    char* sentence = "Test from main \n";
    write(fd, sentence, strlen(sentence));
    printf("Wrote %s from main\n", sentence); 
 
    printf("{MAIN} Writing to the file complete.\n");
    printf("{MAIN} going to sleep for the RUNNER to read from the shared file");
    sleep(2);
    pthread_exit(0);
}