ex: remove PATHLEN
[neatvi.git] / cmd.c
blobd6bc774612067022dd4caf6bd39cc00fc682a986
1 #include <poll.h>
2 #include <signal.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <unistd.h>
7 #include <sys/wait.h>
8 #include "vi.h"
10 static int cmd_make(char **argv, int *ifd, int *ofd)
12 int pid;
13 int pipefds0[2];
14 int pipefds1[2];
15 if (ifd)
16 pipe(pipefds0);
17 if (ofd)
18 pipe(pipefds1);
19 if (!(pid = fork())) {
20 if (ifd) { /* setting up stdin */
21 close(0);
22 dup(pipefds0[0]);
23 close(pipefds0[1]);
24 close(pipefds0[0]);
26 if (ofd) { /* setting up stdout */
27 close(1);
28 dup(pipefds1[1]);
29 close(pipefds1[0]);
30 close(pipefds1[1]);
32 execvp(argv[0], argv);
33 exit(1);
35 if (ifd)
36 close(pipefds0[0]);
37 if (ofd)
38 close(pipefds1[1]);
39 if (pid < 0) {
40 if (ifd)
41 close(pipefds0[1]);
42 if (ofd)
43 close(pipefds1[0]);
44 return -1;
46 if (ifd)
47 *ifd = pipefds0[1];
48 if (ofd)
49 *ofd = pipefds1[0];
50 return pid;
53 char *cmd_pipe(char *cmd, char *s)
55 char *argv[] = {"/bin/sh", "-c", cmd, NULL};
56 struct pollfd fds[3];
57 struct sbuf *sb;
58 char buf[512];
59 int ifd = 0, ofd = 0;
60 int slen = strlen(s);
61 int nw = 0;
62 int pid = cmd_make(argv, &ifd, &ofd);
63 if (pid <= 0)
64 return NULL;
65 sb = sbuf_make();
66 fds[0].fd = ofd;
67 fds[0].events = POLLIN;
68 fds[1].fd = ifd;
69 fds[1].events = POLLOUT;
70 fds[2].fd = 0;
71 fds[2].events = POLLIN;
72 while ((fds[0].fd >= 0 || fds[1].fd >= 0) && poll(fds, 3, 200) >= 0) {
73 if (fds[0].revents & POLLIN) {
74 int ret = read(fds[0].fd, buf, sizeof(buf));
75 if (ret > 0)
76 sbuf_mem(sb, buf, ret);
77 if (ret < 0)
78 close(fds[0].fd);
79 } else if (fds[0].revents & (POLLERR | POLLHUP | POLLNVAL)) {
80 fds[0].fd = -1;
82 if (fds[1].revents & POLLOUT) {
83 int ret = write(fds[1].fd, s + nw, slen - nw);
84 if (ret > 0)
85 nw += ret;
86 if (ret <= 0 || nw == slen)
87 close(fds[1].fd);
88 } else if (fds[1].revents & (POLLERR | POLLHUP | POLLNVAL)) {
89 fds[1].fd = -1;
91 if (fds[2].revents & POLLIN) {
92 int ret = read(fds[2].fd, buf, sizeof(buf));
93 int i;
94 for (i = 0; i < ret; i++)
95 if ((unsigned char) buf[i] == TK_CTL('c'))
96 kill(pid, SIGINT);
97 } else if (fds[0].revents & (POLLERR | POLLHUP | POLLNVAL)) {
98 fds[2].fd = -1;
101 close(ifd);
102 close(ofd);
103 waitpid(pid, NULL, 0);
104 return sbuf_done(sb);
107 int cmd_exec(char *cmd)
109 char *argv[] = {"/bin/sh", "-c", cmd, NULL};
110 int pid = cmd_make(argv, NULL, NULL);
111 if (pid <= 0)
112 return 1;
113 signal(SIGINT, SIG_IGN);
114 term_done();
115 printf("\n");
116 waitpid(pid, NULL, 0);
117 printf("[terminated]\n");
118 getchar();
119 term_init();
120 return 0;