File: open_with_flags.c

package info (click to toggle)
lsof 4.99.4%2Bdfsg-2
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,924 kB
  • sloc: ansic: 50,680; sh: 8,351; makefile: 1,194; perl: 940; awk: 214
file content (63 lines) | stat: -rw-r--r-- 1,263 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#define _GNU_SOURCE

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stdio.h>

struct {
    const char *name;
    int flag;
} table[] = {
    {"path", O_PATH},
    {"cx", O_CLOEXEC},
    {"tmpf", O_TMPFILE},
    {"rdwr", O_RDWR},
};

#define TABLELEN sizeof(table) / sizeof(table[0])

static int encode(const char *const s) {
    for (int i = 0; i < TABLELEN; i++)
        if (!strcmp(s, table[i].name))
            return table[i].flag;
    return 0;
}

static void print_usage(FILE *fp, const char *const prog) {
    fprintf(fp, "Usage:\n");
    fprintf(fp, "	%s FILENAME FLAG ...\n", prog);
    fprintf(fp, "Flags:\n");
    for (int i = 0; i < TABLELEN; i++)
        fprintf(fp, "	%s\n", table[i].name);
}

int main(int argc, char **argv) {

    if (argc < 3) {
        fprintf(stderr, "Too few argument\n");
        print_usage(stderr, argv[0]);
        return 1;
    }

    char *fname = argv[1];
    int flags = 0;

    for (int i = 2; i < argc; i++)
        flags |= encode(argv[i]);

    int fd = open(fname, flags, 0644);
    if (fd < 0) {
        perror("open");
        return 1;
    }

    printf("%d\n", getpid());
    fflush(stdout);
    pause();
    return 0;
}