简体   繁体   中英

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

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.

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, eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM