'write() undefined behavior
I've this code in which I receive a server response, check if it's a successful one, and if it is - create the file under the requested path and then write the response body to the file:
I'm testing it with the following URL:
So it means that I need to create a folder named neverssl.com with an index.html file inside.
I'm creating the file using the following method:
//full_path = "http://neverssl.com/index.html"
int create_file_under_path(char *full_path) {
int fd, path_len = (int) strlen(full_path);
char *curr_path = calloc(path_len + 1, 1);
char *token = strtok(full_path, "/");
strncpy(curr_path, token, path_len);
while (token) {
if (path_len == strlen(curr_path))
break;
if (access(curr_path, F_OK) != 0) {//The folder doesn't exist
if (mkdir(curr_path, S_IRWXU | S_IRWXG | S_IRWXO) == -1) {
perror("mkdir failed\n");
return -1;
}
}
token = strtok(NULL, "/");
strcat(curr_path, "/");
strncat(curr_path, token, strlen(token));
}
if ((fd = open(curr_path, O_CREAT | O_WRONLY, 0700)) == -1) {
perror("failed to open file\n");
return -1;
}
free(curr_path);
return fd;
}
And then I write to it using write system call as follows:
if ((fd = create_file_under_path(url->full_path)) == -1) {
free_URL(url);
free(buf);
exit(EXIT_FAILURE);
}
if (write(fd, buf + header_size, tot_read - header_size) != (buf_size - header_size)) {
perror("write:\n");
exit(EXIT_FAILURE);
}
9 out of 10 times everything works fine, but sometimes even though that the folder and the file are created, write fails with the following message: No such file or directory.
I printed the FD when this happens and it's 4 as it should be.
I've no idea how to procced with debugging it any further and will apricate the help!
Here's an example where you can see that the file exists, the fd is indeed 4 and even so it enters the if statement:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

