GRASS GIS 7 Programmer's Manual  7.5.svn(2017)-r71790
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
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 }
int G_wait(int i_pid)
Definition: spawn.c:955
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
int G_spawn_ex(const char *command,...)
Spawn new process based on command.
Definition: spawn.c:902
#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 pid
Definition: gis.h:577
FILE * G_popen_read(struct Popen *state, const char *program, const char **args)
Definition: popen.c:70
Definition: gis.h:575
fclose(fd)
void G_popen_clear(struct Popen *state)
Definition: popen.c:59
#define SF_CLOSE_DESCRIPTOR
Definition: spawn.h:19
close(fd)
struct state state
Definition: parser.c:102
FILE * fp
Definition: gis.h:576