Root/fakefile/demo.c

Source at commit 51106cf9b34d773e72aa00385c80a9abb76b28df created 5 years 11 months ago.
By Werner Almesberger, ircstat/ML: update for 11/2013
1/*
2 * demo.c - Fakefile demo
3 *
4 * Copyright 2012 by Werner Almesberger
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 */
11
12
13#include <stdlib.h>
14#include <stdio.h>
15#include <string.h>
16
17#include "fakefile.h"
18
19
20static void usage(const char *name)
21{
22    fprintf(stderr,
23        "usage: %s command [arg ...]\n"
24        " %s -e path errno command\n"
25        " %s -f path content command\n",
26        name, name, name);
27    exit(1);
28}
29
30
31int main(int argc, char **argv)
32{
33    struct fakefile *ff;
34    struct fakefile_event *ev;
35    int error = 0;
36    const char *path = NULL, *fake = NULL;
37    char *end;
38
39    if (argc == 1)
40        usage(*argv);
41    if (*argv[1] == '-') {
42        if (argc < 5)
43            usage(*argv);
44        path = argv[2];
45        switch (argv[1][1]) {
46        case 'e':
47            error = strtoul(argv[3], &end, 0);
48            if (*end)
49                usage(*argv);
50            break;
51        case 'f':
52            fake = argv[3];
53            break;
54        default:
55            usage(*argv);
56        }
57        argv += 3;
58    }
59    ff = fakefile_execv(argv[1], argv+1);
60    while (1) {
61        ev = fakefile_poll();
62        switch (ev->type) {
63        case ff_et_open:
64            fprintf(stderr, "\"%s\"\n", ev->u.open.name);
65            if (path && !strcmp(ev->u.open.name, path)) {
66                if (!fake)
67                    ev->u.open.res = -error;
68            } else {
69                ev->u.open.res = 0;
70            }
71            break;
72        case ff_et_read: {
73            size_t len, left;
74
75            len = ev->u.read.len;
76            left = strlen(fake);
77            if (len > left)
78                len = left;
79            ev->u.read.buf = (void *) fake;
80            ev->u.read.len = len;
81            fake += len;
82            break;
83        }
84        case ff_et_exit:
85            goto out;
86        default:
87            break;
88        }
89        fakefile_respond(ev);
90    }
91out:
92    fakefile_end(ff);
93    return 0;
94}
95

Archive Download this file

Branches:
master



interactive