source: trunk/minix/commands/i386/mtools-3.9.7/expand.c@ 20

Last change on this file since 20 was 9, checked in by Mattia Monga, 14 years ago

Minix 3.1.2a

File size: 1.4 KB
Line 
1/*
2 * Do filename expansion with the shell.
3 */
4
5#define EXPAND_BUF 2048
6
7#include "sysincludes.h"
8#include "mtools.h"
9
10
11int safePopenOut(char **command, char *output, int len)
12{
13 int pipefd[2];
14 pid_t pid;
15 int status;
16 int last;
17
18 if(pipe(pipefd)) {
19 return -2;
20 }
21 switch((pid=fork())){
22 case -1:
23 return -2;
24 case 0: /* the son */
25 close(pipefd[0]);
26 destroy_privs();
27 close(1);
28 close(2); /* avoid nasty error messages on stderr */
29 dup(pipefd[1]);
30 close(pipefd[1]);
31 execvp(command[0], command+1);
32 exit(1);
33 default:
34 close(pipefd[1]);
35 break;
36 }
37 last=read(pipefd[0], output, len);
38 kill(pid,9);
39 wait(&status);
40 if(last<0) {
41 return -1;
42 }
43 return last;
44}
45
46
47
48const char *expand(const char *input, char *ans)
49{
50 int last;
51 char buf[256];
52 char *command[] = { "/bin/sh", "sh", "-c", 0, 0 };
53
54 ans[EXPAND_BUF-1]='\0';
55
56 if (input == NULL)
57 return(NULL);
58 if (*input == '\0')
59 return("");
60 /* any thing to expand? */
61 if (!strpbrk(input, "$*(){}[]\\?`~")) {
62 strncpy(ans, input, EXPAND_BUF-1);
63 return(ans);
64 }
65 /* popen an echo */
66#ifdef HAVE_SNPRINTF
67 snprintf(buf, 255, "echo %s", input);
68#else
69 sprintf(buf, "echo %s", input);
70#endif
71
72 command[3]=buf;
73 last=safePopenOut(command, ans, EXPAND_BUF-1);
74 if(last<0) {
75 perror("Pipe read error");
76 exit(1);
77 }
78 if(last)
79 ans[last-1] = '\0';
80 else
81 strncpy(ans, input, EXPAND_BUF-1);
82 return ans;
83}
Note: See TracBrowser for help on using the repository browser.