How do I send and receive messages using read() and write() using a shared file? (C)

124 views Asked by At

So I have two programs, a sender and a receiver that are sending and receiving messages respectively (using a semaphore). This is the code that I have so far.

sender.c

int main(int argc, char *argv[]){
    if(argc != 2){
        printf("%s [message]\n", argv[0]);
        return -1;
    }
    sem_t *semid = sem_open(SEM_NAME, O_CREAT, 00666, 0);
    char *message = argv[1];
    int fd = open("channel.txt", O_WRONLY);
    write(fd, message, strlen(message));
    sem_post(semid);

    sem_close(semid);
    close(fd);
    return 0;
}

receiver.c

int main(int argc, char *argv[]){
    char *buf = malloc(256);
    sem_t *semid = sem_open(SEM_NAME, O_CREAT, 00666, 0);
    int fd = open("channel.txt", O_WRONLY);

    while(TRUE){
        sem_wait(semid);
        lseek(fd, 0, SEEK_SET);
        read(fd, buf, sizeof(buf));
        printf("receiver [msg arrival]: %s\n", buf);
    }

    close(fd);
    free(buf);
    sem_close(semid);
    sem_unlink(SEM_NAME);
    return 0;
}

The sender is able to write the message to the file "channel.txt", but the receiver will always print out a blank message.

1

There are 1 answers

0
slugonamission On BEST ANSWER

There's two things here. First, you're opening write only in the receiver, which may cause your OS to not read from the file.

Also, there's no guarantee that the contents have actually been written to the file before you trigger the semaphore. You should also open your file with the O_SYNC option in order to ensure that any writes have actually been written to the hardware before the write call completes, e.g.

int fd = open("channel.txt", O_WRONLY | O_SYNC);