2 * i3bar - an xcb-based status- and ws-bar for i3
4 * © 2010 Axel Wagner and contributors
6 * See file LICNSE for license information
8 * src/child.c: Getting Input for the statusline
13 #include <sys/types.h>
23 /* Global variables for child_*() */
26 /* stdin- and sigchild-watchers */
31 * Stop and free() the stdin- and sigchild-watchers
35 ev_io_stop(main_loop, stdin_io);
36 ev_child_stop(main_loop, child_sig);
43 * Callbalk for stdin. We read a line from stdin and store the result
47 void stdin_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
51 int buffer_len = STDIN_CHUNK_SIZE;
52 char *buffer = malloc(buffer_len);
53 memset(buffer, '\0', buffer_len);
55 n = read(fd, buffer + rec, buffer_len - rec);
57 if (errno == EAGAIN) {
58 /* remove trailing newline and finish up */
62 ELOG("read() failed!: %s\n", strerror(errno));
66 if (rec == buffer_len) {
67 buffer_len += STDIN_CHUNK_SIZE;
68 buffer = realloc(buffer, buffer_len);
70 /* remove trailing newline and finish up */
77 if (*buffer == '\0') {
88 * We received a sigchild, meaning, that the child-process terminated.
89 * We simply free the respective data-structures and don't care for input
93 void child_sig_cb(struct ev_loop *loop, ev_child *watcher, int revents) {
94 DLOG("Child (pid: %d) unexpectedly exited with status %d\n",
101 * Start a child-process with the specified command and reroute stdin.
102 * We actually start a $SHELL to execute the command so we don't have to care
103 * about arguments and such
106 void start_child(char *command) {
108 if (command != NULL) {
114 ELOG("Couldn't fork(): %s\n", strerror(errno));
117 /* Child-process. Reroute stdout and start shell */
120 dup2(fd[1], STDOUT_FILENO);
122 static const char *shell = NULL;
124 if ((shell = getenv("SHELL")) == NULL)
127 execl(shell, shell, "-c", command, (char*) NULL);
130 /* Parent-process. Rerout stdin */
133 dup2(fd[0], STDIN_FILENO);
135 /* If hide-on-modifier is set, we start of by sending the
136 * child a SIGSTOP, because the bars aren't mapped at start */
143 /* We set O_NONBLOCK because blocking is evil in event-driven software */
144 fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
146 stdin_io = malloc(sizeof(ev_io));
147 ev_io_init(stdin_io, &stdin_io_cb, STDIN_FILENO, EV_READ);
148 ev_io_start(main_loop, stdin_io);
150 /* We must cleanup, if the child unexpectedly terminates */
151 child_sig = malloc(sizeof(ev_child));
152 ev_child_init(child_sig, &child_sig_cb, child_pid, 0);
153 ev_child_start(main_loop, child_sig);
158 * kill()s the child-process (if existent) and closes and
159 * free()s the stdin- and sigchild-watchers
163 if (child_pid != 0) {
164 kill(child_pid, SIGCONT);
165 kill(child_pid, SIGTERM);
171 * Sends a SIGSTOP to the child-process (if existent)
175 if (child_pid != 0) {
176 kill(child_pid, SIGSTOP);
181 * Sends a SIGCONT to the child-process (if existent)
185 if (child_pid != 0) {
186 kill(child_pid, SIGCONT);