vi: explain when the screen is updated in vi()
[neatvi.git] / cmd.c
blob5993e8a93b7f96db3f551b75c723a0021be16e0f
1 #include <fcntl.h>
2 #include <poll.h>
3 #include <signal.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <unistd.h>
8 #include <sys/wait.h>
9 #include "vi.h"
11 static int cmd_make(char **argv, int *ifd, int *ofd)
13 int pid;
14 int pipefds0[2];
15 int pipefds1[2];
16 if (ifd)
17 pipe(pipefds0);
18 if (ofd)
19 pipe(pipefds1);
20 if (!(pid = fork())) {
21 if (ifd) { /* setting up stdin */
22 close(0);
23 dup(pipefds0[0]);
24 close(pipefds0[1]);
25 close(pipefds0[0]);
27 if (ofd) { /* setting up stdout */
28 close(1);
29 dup(pipefds1[1]);
30 close(pipefds1[0]);
31 close(pipefds1[1]);
33 execvp(argv[0], argv);
34 exit(1);
36 if (ifd)
37 close(pipefds0[0]);
38 if (ofd)
39 close(pipefds1[1]);
40 if (pid < 0) {
41 if (ifd)
42 close(pipefds0[1]);
43 if (ofd)
44 close(pipefds1[0]);
45 return -1;
47 if (ifd)
48 *ifd = pipefds0[1];
49 if (ofd)
50 *ofd = pipefds1[0];
51 return pid;
54 /* execute a command; process input if iproc and process output if oproc */
55 char *cmd_pipe(char *cmd, char *ibuf, int iproc, int oproc)
57 char *argv[] = {"/bin/sh", "-c", cmd, NULL};
58 struct pollfd fds[3];
59 struct sbuf *sb = NULL;
60 char buf[512];
61 int ifd = -1, ofd = -1;
62 int slen = iproc ? strlen(ibuf) : 0;
63 int nw = 0;
64 int pid = cmd_make(argv, iproc ? &ifd : NULL, oproc ? &ofd : NULL);
65 if (pid <= 0)
66 return NULL;
67 if (oproc)
68 sb = sbuf_make();
69 if (!iproc) {
70 signal(SIGINT, SIG_IGN);
71 term_done();
73 fcntl(ifd, F_SETFL, fcntl(ifd, F_GETFL, 0) | O_NONBLOCK);
74 fds[0].fd = ofd;
75 fds[0].events = POLLIN;
76 fds[1].fd = ifd;
77 fds[1].events = POLLOUT;
78 fds[2].fd = iproc ? 0 : -1;
79 fds[2].events = POLLIN;
80 while ((fds[0].fd >= 0 || fds[1].fd >= 0) && poll(fds, 3, 200) >= 0) {
81 if (fds[0].revents & POLLIN) {
82 int ret = read(fds[0].fd, buf, sizeof(buf));
83 if (ret > 0)
84 sbuf_mem(sb, buf, ret);
85 if (ret < 0)
86 close(fds[0].fd);
87 } else if (fds[0].revents & (POLLERR | POLLHUP | POLLNVAL)) {
88 fds[0].fd = -1;
90 if (fds[1].revents & POLLOUT) {
91 int ret = write(fds[1].fd, ibuf + nw, slen - nw);
92 if (ret > 0)
93 nw += ret;
94 if (ret <= 0 || nw == slen)
95 close(fds[1].fd);
96 } else if (fds[1].revents & (POLLERR | POLLHUP | POLLNVAL)) {
97 fds[1].fd = -1;
99 if (fds[2].revents & POLLIN) {
100 int ret = read(fds[2].fd, buf, sizeof(buf));
101 int i;
102 for (i = 0; i < ret; i++)
103 if ((unsigned char) buf[i] == TK_CTL('c'))
104 kill(pid, SIGINT);
105 } else if (fds[0].revents & (POLLERR | POLLHUP | POLLNVAL)) {
106 fds[2].fd = -1;
109 close(ifd);
110 close(ofd);
111 waitpid(pid, NULL, 0);
112 if (!iproc) {
113 term_init();
114 signal(SIGINT, SIG_DFL);
116 if (oproc)
117 return sbuf_done(sb);
118 return NULL;
121 int cmd_exec(char *cmd)
123 cmd_pipe(cmd, NULL, 0, 0);
124 return 0;