Domanda

Say I'm sending a file from a server to a client using read & send system call. Now, I want to receive the data at the client side using mmap system call. how do I do that?

given the following send_file function (Server side) : (sd is the socket descriptor associated with the client)

int send_file (int sd, const char* file_name) {

int fd;
char buf[1024];
if ( (fd =get_fd(file_name)) > 0) {

    while (read(fd, buf, sizeof buf) > 0) {

        if (send(sd, buf, sizeof buf, 0) < 0) {
            perror("send");
            return -1;
        }

    }

    close(fd);
    return 0;

}

return -1;

}

Again, I want to create the file at the client's side and then use MMAP to store the file from the server. How do I do that? would love to get some suggestions.

thanks in advance

È stato utile?

Soluzione

You can't receive a file from a socket using mmap. mmap is used to map files (or anonymous memory) into your process virtual adress space. Quoting the man page

mmap() creates a new mapping in the virtual address space of the calling process.

So you have to use "sockets calls" to receive the file at the client side.

Not sure to understand why you want to do that, here is a way using mmap to write into the file at client side. First you have to use fopen(). You can then use lseek to "enlarge" the file:

The lseek() function allows the file offset to be set beyond the end of the file (but this does not change the size of the file). If data is later written at this point, subse‐ quent reads of the data in the gap (a "hole") return null bytes ('\0') until data is actually written into the gap.

And finally you can mmap it and copy the content received through network.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top