, , pipe().
, , tee, :
int child_pipe[2];
pid_t pid_exec_child, pid_output_child;
pipe(child_pipe);
pid_exec_child = fork();
if (pid_exec_child == 0)
{
dup2(child_pipe[1], STDOUT_FILENO);
close(child_pipe[0]);
close(child_pipe[1]);
execve();
_exit(127);
}
close(child_pipe[1]);
pid_output_child = fork();
if (pid_output_child == 0)
{
int logfd = open("logfile", O_WRONLY);
char buffer[4096];
ssize_t nread;
while ((nread = read(child_pipe[0], buffer, sizeof buffer) != 0)
{
size_t nwritten_total;
ssize_t nwritten;
if (nread < 0)
{
if (errno == EINTR)
continue;
perror("read");
_exit(1);
}
nwritten_total = 0;
while (nwritten_total < nread)
{
nwritten = write(STDOUT_FILENO, buffer + nwritten_total, nread - nwritten_total);
if (nwritten < 0)
{
if (errno == EINTR)
continue;
perror("write(stdout)");
_exit(2);
}
nwritten_total += nwritten;
}
nwritten_total = 0;
while (nwritten_total < nread)
{
nwritten = write(logfd, buffer + nwritten_total, nread - nwritten_total);
if (nwritten < 0)
{
if (errno == EINTR)
continue;
perror("write(logfile)");
_exit(3);
}
nwritten_total += nwritten;
}
}
_exit(0);
}
close(child_pipe[0]);
, exec tee ...
( , _exit(), - ).