|
| 1 | +/* |
| 2 | + * Copyright 2024 The Emscripten Authors. All rights reserved. |
| 3 | + * Emscripten is available under two separate licenses, the MIT license and the |
| 4 | + * University of Illinois/NCSA Open Source License. Both these licenses can be |
| 5 | + * found in the LICENSE file. |
| 6 | + */ |
| 7 | + |
| 8 | +#include <assert.h> |
| 9 | +#include <errno.h> |
| 10 | +#include <fcntl.h> |
| 11 | +#include <signal.h> |
| 12 | +#include <stdio.h> |
| 13 | +#include <stdlib.h> |
| 14 | +#include <string.h> |
| 15 | +#include <unistd.h> |
| 16 | +#include <sys/stat.h> |
| 17 | +#include <sys/types.h> |
| 18 | + |
| 19 | +mode_t get_umask() { |
| 20 | + mode_t current = umask(0); // Set umask to 0 and get the old value |
| 21 | + umask(current); // Immediately set it back |
| 22 | + return current; |
| 23 | +} |
| 24 | + |
| 25 | +void create_file(const char *path, const char *buffer) { |
| 26 | + mode_t mode = 0777 - get_umask(); |
| 27 | + int fd = open(path, O_WRONLY | O_CREAT | O_EXCL, mode); |
| 28 | + assert(fd >= 0); |
| 29 | + |
| 30 | + int err = write(fd, buffer, sizeof(char) * strlen(buffer)); |
| 31 | + assert(err == (sizeof(char) * strlen(buffer))); |
| 32 | + |
| 33 | + close(fd); |
| 34 | +} |
| 35 | + |
| 36 | +int main() { |
| 37 | + // Get the default umask |
| 38 | + mode_t default_umask = get_umask(); |
| 39 | + printf("default umask: %o\n", default_umask); |
| 40 | + assert(default_umask == 022); |
| 41 | + |
| 42 | + // Create a new file with default umask |
| 43 | + create_file("umask_test_file", "abcdef"); |
| 44 | + struct stat st; |
| 45 | + stat("umask_test_file", &st); |
| 46 | + printf("default_umask - stat: %o\n", st.st_mode); |
| 47 | + assert((st.st_mode & 0666) == 0644); |
| 48 | + unlink("umask_test_file"); |
| 49 | + |
| 50 | + // Set new umask |
| 51 | + mode_t new_umask = 027; |
| 52 | + mode_t old_umask = umask(new_umask); |
| 53 | + |
| 54 | + // Create a new file with new umask |
| 55 | + create_file("umask_test_file", "abcdef"); |
| 56 | + stat("umask_test_file", &st); |
| 57 | + printf("new_umask - stat: %o\n", st.st_mode); |
| 58 | + assert((st.st_mode & 0666) == 0640); |
| 59 | + |
| 60 | + // Restore the old umask |
| 61 | + umask(old_umask); |
| 62 | + |
| 63 | + puts("success"); |
| 64 | + return EXIT_SUCCESS; |
| 65 | +} |
0 commit comments