GRASS GIS 8 Programmer's Manual  8.5.0dev(2024)-602118adcc
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 
15 static 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,
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 
56 void G_popen_clear(struct Popen *state)
57 {
58  state->fp = NULL;
59  state->pid = -1;
60 }
61 
62 FILE *G_popen_write(struct Popen *state, const char *program, const char **args)
63 {
64  return do_popen(state, 1, program, args);
65 }
66 
67 FILE *G_popen_read(struct Popen *state, const char *program, const char **args)
68 {
69  return do_popen(state, 0, program, args);
70 }
71 
72 void 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
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
struct state state
Definition: parser.c:103
FILE * G_popen_read(struct Popen *state, const char *program, const char **args)
Definition: popen.c:67
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_write(struct Popen *state, const char *program, const char **args)
Definition: popen.c:62
#define SF_ARGVEC
Definition: spawn.h:25
#define SF_CLOSE_DESCRIPTOR
Definition: spawn.h:19
#define SF_REDIRECT_DESCRIPTOR
Definition: spawn.h:18
#define SF_BACKGROUND
Definition: spawn.h:23
Definition: gis.h:623