21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

SPC_PIPE *spc_popen(const char *path, char *const argv[], char *const envp[]) {<br />

int stdin_pipe[2], stdout_pipe[2];<br />

SPC_PIPE *p;<br />

if (!(p = (SPC_PIPE *)malloc(sizeof(SPC_PIPE)))) return 0;<br />

p->read_fd = p->write_fd = 0;<br />

p->child_pid = -1;<br />

if (pipe(stdin_pipe) = = -1) {<br />

free(p);<br />

return 0;<br />

}<br />

if (pipe(stdout_pipe) = = -1) {<br />

close(stdin_pipe[1]);<br />

close(stdin_pipe[0]);<br />

free(p);<br />

return 0;<br />

}<br />

if (!(p->read_fd = fdopen(stdout_pipe[0], "r"))) {<br />

close(stdout_pipe[1]);<br />

close(stdout_pipe[0]);<br />

close(stdin_pipe[1]);<br />

close(stdin_pipe[0]);<br />

free(p);<br />

return 0;<br />

}<br />

if (!(p->write_fd = fdopen(stdin_pipe[1], "w"))) {<br />

fclose(p->read_fd);<br />

close(stdout_pipe[1]);<br />

close(stdin_pipe[1]);<br />

close(stdin_pipe[0]);<br />

free(p);<br />

return 0;<br />

}<br />

if ((p->child_pid = spc_fork( )) = = -1) {<br />

fclose(p->write_fd);<br />

fclose(p->read_fd);<br />

close(stdout_pipe[1]);<br />

close(stdin_pipe[0]);<br />

free(p);<br />

return 0;<br />

}<br />

if (!p->child_pid) {<br />

/* this is the child process */<br />

close(stdout_pipe[0]);<br />

close(stdin_pipe[1]);<br />

if (stdin_pipe[0] != 0) {<br />

dup2(stdin_pipe[0], 0);<br />

close(stdin_pipe[0]);<br />

}<br />

if (stdout_pipe[1] != 1) {<br />

32 | Chapter 1: Safe Initialization<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!