GRASS GIS 8 Programmer's Manual  8.2.2dev(2023)-3d2c704037
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,
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,
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 
59 void G_popen_clear(struct Popen *state)
60 {
61  state->fp = NULL;
62  state->pid = -1;
63 }
64 
65 FILE *G_popen_write(struct Popen *state, const char *program, const char **args)
66 {
67  return do_popen(state, 1, program, args);
68 }
69 
70 FILE *G_popen_read(struct Popen *state, const char *program, const char **args)
71 {
72  return do_popen(state, 0, program, args);
73 }
74 
75 void 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 }
void G_popen_close(struct Popen *state)
Definition: popen.c:75
FILE * G_popen_write(struct Popen *state, const char *program, const char **args)
Definition: popen.c:65
#define SF_ARGVEC
Definition: spawn.h:25
#define SF_REDIRECT_DESCRIPTOR
Definition: spawn.h:18
#define NULL
Definition: ccmath.h:32
#define SF_BACKGROUND
Definition: spawn.h:23
int G_spawn_ex(const char *command,...)
Spawn new process based on command.
Definition: spawn.c:903
int pid
Definition: gis.h:610
FILE * G_popen_read(struct Popen *state, const char *program, const char **args)
Definition: popen.c:70
int G_wait(int i_pid)
Definition: spawn.c:956
Definition: gis.h:608
void G_popen_clear(struct Popen *state)
Definition: popen.c:59
#define SF_CLOSE_DESCRIPTOR
Definition: spawn.h:19
struct state state
Definition: parser.c:103
FILE * fp
Definition: gis.h:609