2013-01-23 17:38:08 +00:00
|
|
|
/* radare - LGPL - Copyright 2009-2013 - pancake */
|
2009-02-05 21:08:46 +00:00
|
|
|
|
|
|
|
#include <r_cons.h>
|
|
|
|
#include <unistd.h>
|
2011-11-16 01:06:46 +00:00
|
|
|
#include <limits.h>
|
2009-02-05 21:08:46 +00:00
|
|
|
|
|
|
|
//TODO: cons_pipe should be using a stack pipe_push, pipe_pop
|
|
|
|
/* this is the base fd.. more than one is supported :) */
|
2011-11-15 23:44:18 +00:00
|
|
|
static int backup_fd = -1;
|
2013-11-29 16:27:46 +00:00
|
|
|
static int backup_fdn = 1;
|
2009-02-05 21:08:46 +00:00
|
|
|
|
2011-11-29 11:28:02 +00:00
|
|
|
#ifndef O_BINARY
|
|
|
|
#define O_BINARY 0
|
|
|
|
#endif
|
|
|
|
|
2013-11-29 16:27:46 +00:00
|
|
|
R_API int r_cons_pipe_open(const char *file, int fdn, int append) {
|
2013-01-23 17:38:08 +00:00
|
|
|
int fd = r_sandbox_open (file,
|
2013-09-26 23:38:49 +00:00
|
|
|
O_BINARY | O_RDWR | O_CREAT | (append? O_APPEND: O_TRUNC), 0644);
|
2009-02-05 21:08:46 +00:00
|
|
|
if (fd==-1) {
|
2012-09-06 10:47:32 +00:00
|
|
|
eprintf ("r_cons_pipe_open: Cannot open file '%s'\n", file);
|
2009-02-05 21:08:46 +00:00
|
|
|
return -1;
|
2012-08-13 11:16:06 +00:00
|
|
|
}// else eprintf ("%s created\n", file);
|
2011-11-29 11:28:02 +00:00
|
|
|
if (backup_fd != -1)
|
2011-11-15 23:44:18 +00:00
|
|
|
close (backup_fd);
|
2013-11-29 16:27:46 +00:00
|
|
|
backup_fdn = (fdn>0)? fdn: 1;
|
2014-06-25 12:52:01 +00:00
|
|
|
#if __WINDOWS__ && !__CYGWIN__
|
2011-11-16 01:06:46 +00:00
|
|
|
backup_fd = 2002-(fd-2); // windows xp has 2048 as limit fd
|
2013-11-29 16:27:46 +00:00
|
|
|
if (_dup2 (fdn, backup_fd) == -1) {
|
2011-11-16 01:06:46 +00:00
|
|
|
#else
|
2011-11-15 23:44:18 +00:00
|
|
|
backup_fd = sysconf (_SC_OPEN_MAX)-(fd-2); // portable getdtablesize()
|
2013-09-26 23:38:49 +00:00
|
|
|
if (backup_fd <2) backup_fd = 2002-(fd-2); // fallback
|
2013-11-29 16:27:46 +00:00
|
|
|
if (dup2 (fdn, backup_fd) == -1) {
|
2011-11-16 01:06:46 +00:00
|
|
|
#endif
|
2011-04-04 16:33:27 +00:00
|
|
|
eprintf ("Cannot dup stdout to %d\n", backup_fd);
|
|
|
|
return -1;
|
|
|
|
}
|
2013-11-29 16:27:46 +00:00
|
|
|
close (fdn);
|
|
|
|
dup2 (fd, fdn);
|
2009-02-05 21:08:46 +00:00
|
|
|
return fd;
|
|
|
|
}
|
|
|
|
|
2010-07-12 19:37:40 +00:00
|
|
|
R_API void r_cons_pipe_close(int fd) {
|
2009-02-05 21:08:46 +00:00
|
|
|
if (fd == -1)
|
|
|
|
return;
|
2011-04-04 16:33:27 +00:00
|
|
|
close (fd);
|
2011-11-15 23:44:18 +00:00
|
|
|
if (backup_fd != -1) {
|
2013-11-29 16:27:46 +00:00
|
|
|
dup2 (backup_fd, backup_fdn);
|
2011-11-15 23:44:18 +00:00
|
|
|
close (backup_fd);
|
|
|
|
backup_fd = -1;
|
|
|
|
}
|
2009-02-05 21:08:46 +00:00
|
|
|
}
|