brandonspark
brandonspark

Reputation: 1

Sequential write calls to the same file descriptor, but only the second crashes?

I am currently writing a C program that is writing some data to a file descriptor, where the file descriptor represents some other process that has opened a connection to the program.

My program invariably crashes at a certain point, and I have narrowed down the last few actions that it has taken, which looks something like:

write(clientfd, "start", 5);
printf("something goes here");
write(clientfd, "end", 3);
printf("something else goes here");

The writes are to the same file descriptor, and writing basic string literals - however, in the course of this program's execution, only the first write and printf go off - the program appears to crash at the second write, as the second printf never appears.

This doesn't seem to make much sense to me. I've also printed out the output of the first write (the number of bytes that it actually wrote), and it appears to be correct (5 in this instance), meaning that the first write call didn't even fail, but the second one causes the program to crash for some arcane reason. It may be important to note that, for this file descriptor connection, on the client's side of the connection, the client has already closed their end of the file descriptor. I wasn't sure if that was relevant or not, but I felt that it wasn't, since the first write succeeded.

Upvotes: 0

Views: 394

Answers (1)

89f3a1c
89f3a1c

Reputation: 1488

for this file descriptor connection, on the client's side of the connection, the client has already closed their end of the file descriptor.

From the man page, I guess you're getting one of the following errors:

  • EBADF fd is not a valid file descriptor or is not open for writing.
  • EPIPE fd is connected to a pipe or socket whose reading end is closed. When this happens the writing process will also receive a SIGPIPE signal. (Thus, the write return value is seen only if the program catches, blocks or ignores this signal.)

I suggest you check the return value, and in case of error, make sure you inspect it with perror().

On error, -1 is returned, and errno is set appropriately.

Upvotes: 1

Related Questions