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 /* stdin- and sigchild-watchers */
28 * Stop and free() the stdin- and sigchild-watchers
32 ev_io_stop(main_loop, stdin_io);
33 ev_child_stop(main_loop, child_sig);
40 * Callbalk for stdin. We read a line from stdin and store the result
44 void stdin_io_cb(struct ev_loop *loop, ev_io *watcher, int revents) {
48 int buffer_len = STDIN_CHUNK_SIZE;
49 char *buffer = malloc(buffer_len);
50 memset(buffer, '\0', buffer_len);
52 n = read(fd, buffer + rec, buffer_len - rec);
54 if (errno == EAGAIN) {
55 /* remove trailing newline and finish up */
59 printf("ERROR: read() failed!");
63 if (rec == buffer_len) {
65 buffer = malloc(buffer_len + STDIN_CHUNK_SIZE);
66 memset(buffer, '\0', buffer_len);
67 strncpy(buffer, tmp, buffer_len);
68 buffer_len += STDIN_CHUNK_SIZE;
71 /* remove trailing newline and finish up */
78 if (strlen(buffer) == 0) {
84 printf("%s\n", buffer);
89 * We received a sigchild, meaning, that the child-process terminated.
90 * We simply free the respective data-structures and don't care for input
94 void child_sig_cb(struct ev_loop *loop, ev_child *watcher, int revents) {
95 printf("Child (pid: %d) unexpectedly exited with status %d\n",
102 * Start a child-process with the specified command and reroute stdin.
103 * We actually start a $SHELL to execute the command so we don't have to care
104 * about arguments and such
107 void start_child(char *command) {
109 if (command != NULL) {
115 printf("ERROR: Couldn't fork()");
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);
132 dup2(fd[0], STDIN_FILENO);
138 fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
140 stdin_io = malloc(sizeof(ev_io));
141 ev_io_init(stdin_io, &stdin_io_cb, STDIN_FILENO, EV_READ);
142 ev_io_start(main_loop, stdin_io);
144 /* We must cleanup, if the child unexpectedly terminates */
145 child_sig = malloc(sizeof(ev_io));
146 ev_child_init(child_sig, &child_sig_cb, child_pid, 0);
147 ev_child_start(main_loop, child_sig);
152 * kill()s the child-process (if existent) and closes and
153 * free()s the stdin- and sigchild-watchers
157 if (child_pid != 0) {
158 kill(child_pid, SIGQUIT);
164 * Sends a SIGSTOP to the child-process (if existent)
168 if (child_pid != 0) {
169 kill(child_pid, SIGSTOP);
174 * Sends a SIGCONT to the child-process (if existent)
178 if (child_pid != 0) {
179 kill(child_pid, SIGCONT);