简体   繁体   中英

Using write() to write the bytes of a variable to a file descriptor?

I'm trying to send raw bytes of a variable to a certain file descriptor (in this case a socket).

So let's say I have:

size_t number = 3;
write(some_fd, number, sizeof(size_t));

So would that write the sizeof(size_t) number of bytes of the variable number to the file descriptor some_fd ?

I have no way of testing this out currently, so just wanted to confrm.

So would that write the sizeof(size_t) number of bytes of the variable number to the file descriptor some_fd ?

No, it won't.

Remember that write is declared as:

ssize_t write(int fildes, const void *buf, size_t nbyte);

You'd need to use:

write(some_fd, &number, sizeof(size_t));
//             ^^^

Use of & is necessary to be able write the value of number from the address used by number .

write expects address of the buffer which has the data that need to be written. So you need to pass address of number in your case.

write can be interrupted. You need to check the return value of the write to know whether the expected number of bytes are successfully written or not. Below are the lines from write man page:

The number of bytes written may be less than count if, for example, there is insufficient space on the underlying physical medium or the call was interrupted by a signal handler after having written less than count bytes.

If a write() is interrupted by a signal handler before any bytes are written, then the call fails with the error EINTR; if it is interrupted after at least one byte has been written, the call succeeds, and returns the number of bytes written.

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