Root/libbb/libbb.c

Source at commit 3f820dc41d82c78d972efe3c69f139f209a742f9 created 9 years 16 days ago.
By Werner Almesberger, cad/test2/README: added more results and cleaned up the text
1/*
2 * libbb/libbb.c - Bitbang library
3 *
4 * Written 2010 by Werner Almesberger
5 * Copyright 2010 Werner Almesberger
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 */
12
13
14#include <stdlib.h>
15#include <stdio.h>
16#include <unistd.h>
17#include <string.h>
18#include <sys/types.h>
19#include <sys/socket.h>
20//#include <sys/wait.h>
21#include <sys/mman.h>
22
23#include "libbb.h"
24
25
26#define PAGE_SIZE 4096
27
28
29volatile void *libbb_mem;
30
31static int bbd_fd = -1;
32
33
34static int recv_fd(int s)
35{
36    struct msghdr msg;
37    struct cmsg {
38        struct cmsghdr hdr;
39        int fd;
40    } cmsg;
41
42    memset(&msg, 0, sizeof(msg));
43    msg.msg_control = &cmsg;
44    msg.msg_controllen = sizeof(cmsg);
45        if (recvmsg(s, &msg, 0) < 0) {
46        perror("recvmsg");
47        exit(1);
48    }
49    return cmsg.fd;
50}
51
52
53static void child(void)
54{
55    execl(LIBBD_PATH, LIBBD_PATH, NULL);
56    perror(LIBBD_PATH);
57    _exit(1);
58}
59
60
61#if 0
62static int recv_fd(int s)
63{
64    pid_t res;
65
66    res = waitpid(pid, &status, 0);
67    if (res < 0) {
68        perror("waitpid");
69        exit(1);
70    }
71    if (res != pid) {
72        fprintf(stderr, "waitpid returned %d for %d\n",
73            (int) res, (int) pid);
74        exit(1);
75    }
76}
77#endif
78
79
80static int bbd(void)
81{
82    int s[2];
83    pid_t pid;
84
85    if (socketpair(PF_LOCAL, SOCK_DGRAM, 0, s) < 0) {
86        perror("socketpair");
87        exit(1);
88    }
89    if (dup2(s[1], 1) < 0) {
90        perror("dup2");
91        exit(1);
92    }
93
94    pid = fork();
95    if (pid < 0) {
96        perror("fork");
97        exit(1);
98    }
99    if (pid)
100        return recv_fd(s[0]);
101    else
102        child();
103    return -1; /* can't happen */
104}
105
106
107void libbb_open(void)
108{
109    bbd_fd = bbd();
110    libbb_mem = mmap(NULL, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED,
111       bbd_fd, LIBBB_GPIO_BASE);
112    if (libbb_mem == MAP_FAILED) {
113        perror("mmap");
114        exit(1);
115    }
116}
117
118
119
120void libbb_close(void)
121{
122    if (close(bbd_fd) < 0) {
123        perror("close");
124        exit(1);
125    }
126}
127

Archive Download this file

Branches:
master



interactive