Click here to Skip to main content
15,887,368 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hello how two create tow threads to write and read at the same file (in c language)
any advice please.....:)

What I have tried:

??????????????????????????????????????????
Posted
Updated 13-Jul-18 2:24am

I would use a memory-mapped file. I know how to use them in Windows fairly well and there are lots of samples for that but I know very little about using them in Linux.
 
Share this answer
 
You have to use some kind of locking mechanism for the file (see File locking in Linux[^]), or - when the threads belong to the same process and you have a shared file descriptor / handle - the code blocks that are writing to the file.

If the threads belong to the same process I would use a shared file descriptor and the locking mechanisms of the used thread type like pthread_mutex_lock(3): lock/unlock mutex - Linux man page[^] with pthread.
 
Share this answer
 
This is just an example of read/write with synchronization using file locks. There are not any error checks or stuff like that.
C++
#include <unistd.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>

int fd;
off_t read_offset;
int q = 0;

void* reader_routine(void* p)
{
    char buffer[32] = {0};
    int bytesRead = 0;

    while(!q)
    {
        flock(fd, LOCK_EX);
        lseek(fd, read_offset, SEEK_SET);
        bytesRead = read(fd, buffer, 32);
        flock(fd, LOCK_UN);
        if (bytesRead > 0)
        {
            read_offset = lseek(fd, read_offset + bytesRead, SEEK_SET);
            buffer[bytesRead] = 0;
            puts(buffer);
        }
    }

    lseek(fd, read_offset, SEEK_SET);
    bytesRead = read(fd, buffer, 32);
    if (bytesRead > 0)
    {
        buffer[bytesRead] = 0;
        puts(buffer);
    }
    return NULL;
}

int main()
{
    pthread_t th;
    const char* const numbers[] = { "one", "two", "three", "four", "five" };
    fd = open("file.txt", O_RDWR | O_CREAT | O_TRUNC, S_IRWXU | S_IRWXG);
    srand(time(NULL));

    read_offset = lseek(fd, SEEK_SET, 0);
    pthread_create(&th, NULL, reader_routine, NULL);
    for(int i = 0; i < 5; ++i)
    {
        flock(fd, LOCK_EX);
        sleep(rand()%5);
        lseek(fd, 0, SEEK_END);
        write(fd, numbers[i], strlen(numbers[i]));
        flock(fd, LOCK_UN);
    }
    q = 1;
    pthread_join(th, NULL);
    close(fd);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900