GRASS GIS 8 Programmer's Manual 8.2.1(2023)-exported
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,
16 const char *program, 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 = G_spawn_ex(
40 program,
41 SF_ARGVEC, args,
42 SF_REDIRECT_DESCRIPTOR, which, cfd,
43 SF_CLOSE_DESCRIPTOR, pfd,
44 SF_BACKGROUND, NULL);
45
46 if (state->pid == -1) {
47 close(pipe_fds[0]);
48 close(pipe_fds[1]);
49 return NULL;
50 }
51
52 close(cfd);
53
54 state->fp = fdopen(pfd, dir);
55
56 return state->fp;
57}
58
59void G_popen_clear(struct Popen *state)
60{
61 state->fp = NULL;
62 state->pid = -1;
63}
64
65FILE *G_popen_write(struct Popen *state, const char *program, const char **args)
66{
67 return do_popen(state, 1, program, args);
68}
69
70FILE *G_popen_read(struct Popen *state, const char *program, const char **args)
71{
72 return do_popen(state, 0, program, args);
73}
74
75void G_popen_close(struct Popen *state)
76{
77 if (state->fp)
78 fclose(state->fp);
79
80 if (state->pid != -1)
81 G_wait(state->pid);
82}
#define NULL
Definition: ccmath.h:32
struct state state
Definition: parser.c:103
void G_popen_close(struct Popen *state)
Definition: popen.c:75
void G_popen_clear(struct Popen *state)
Definition: popen.c:59
FILE * G_popen_read(struct Popen *state, const char *program, const char **args)
Definition: popen.c:70
FILE * G_popen_write(struct Popen *state, const char *program, const char **args)
Definition: popen.c:65
int G_wait(int i_pid)
Definition: spawn.c:956
int G_spawn_ex(const char *command,...)
Spawn new process based on command.
Definition: spawn.c:903