GRASS GIS 8 Programmer's Manual 8.3.2(2024)-exported
Loading...
Searching...
No Matches
popen.c
Go to the documentation of this file.
1#include <stdio.h>
2#include <stdlib.h>
3
4#include <unistd.h>
5
6#include <grass/gis.h>
7#include <grass/spawn.h>
8
9#ifdef __MINGW32__
10#include <io.h>
11#include <fcntl.h>
12#define pipe(fds) _pipe(fds, 4096, O_BINARY | O_NOINHERIT)
13#endif
14
15static FILE *do_popen(struct Popen *state, int wr, const char *program,
16 const char **args)
17{
18 int which = wr ? 0 : 1;
19 const char *dir = wr ? "w" : "r";
20 int pfd, cfd;
21 int pipe_fds[2];
22 const char *argv[2];
23
24 state->fp = NULL;
25 state->pid = -1;
26
27 if (pipe(pipe_fds) < 0)
28 return NULL;
29
30 cfd = pipe_fds[wr ? 0 : 1];
31 pfd = pipe_fds[wr ? 1 : 0];
32
33 if (!args) {
34 argv[0] = program;
35 argv[1] = NULL;
36 args = argv;
37 }
38
39 state->pid =
40 G_spawn_ex(program, SF_ARGVEC, args, SF_REDIRECT_DESCRIPTOR, which, cfd,
41 SF_CLOSE_DESCRIPTOR, pfd, SF_BACKGROUND, NULL);
42
43 if (state->pid == -1) {
44 close(pipe_fds[0]);
45 close(pipe_fds[1]);
46 return NULL;
47 }
48
49 close(cfd);
50
51 state->fp = fdopen(pfd, dir);
52
53 return state->fp;
54}
55
56void G_popen_clear(struct Popen *state)
57{
58 state->fp = NULL;
59 state->pid = -1;
60}
61
62FILE *G_popen_write(struct Popen *state, const char *program, const char **args)
63{
64 return do_popen(state, 1, program, args);
65}
66
67FILE *G_popen_read(struct Popen *state, const char *program, const char **args)
68{
69 return do_popen(state, 0, program, args);
70}
71
72void G_popen_close(struct Popen *state)
73{
74 if (state->fp)
75 fclose(state->fp);
76
77 if (state->pid != -1)
78 G_wait(state->pid);
79}
#define NULL
Definition ccmath.h:32
void G_popen_close(struct Popen *state)
Definition popen.c:72
void G_popen_clear(struct Popen *state)
Definition popen.c:56
FILE * G_popen_read(struct Popen *state, const char *program, const char **args)
Definition popen.c:67
FILE * G_popen_write(struct Popen *state, const char *program, const char **args)
Definition popen.c:62
int G_wait(int i_pid)
Definition spawn.c:949
int G_spawn_ex(const char *command,...)
Spawn new process based on command.
Definition spawn.c:897