- 论坛徽章:
- 0
|
#include
#include
#include
#include
#include
void signal_handler();
void sig_chld(int signo);
void err_sys(const char *errmsg);
int main(void)
{
int fd[2];
pid_t pid;
char buf[BUFSIZ];
ssize_t n;
signal_handler(); /* handler SIGCHLD */
if (pipe(fd) == -1) /* create pipe */
err_sys("pipe");
if ((pid = fork()) == -1)
err_sys("fork");
else if (!pid) { /* child process */
if (close(fd[0]) == -1)
err_sys("close");
if ((n = read(STDIN_FILENO, buf, sizeof(buf))) == -1)
err_sys("read");
else if (write(fd[1], buf, n) != n)
err_sys("write");
exit(0);
}
if (close(fd[1]) == -1)
err_sys("close");
if ((n = read(fd[0], buf, sizeof(buf))) == -1)
err_sys("read");
else if (write(STDOUT_FILENO, buf, n) != n)
err_sys("write");
exit(0);
}
void signal_handler(void)
{
struct sigaction act;
act.sa_handler = sig_chld;
act.sa_flags = 0;
if (sigemptyset(&act.sa_mask) == -1)
err_sys("sigemptyset");
else if (sigaction(SIGCHLD, &act, NULL) == -1)
err_sys("sigaction");
}
void sig_chld(int signo)
{
while(waitpid(-1, NULL, WNOHANG) > 0)
/* wait child process */;
}
void err_sys(const char *errmsg)
{
perror(errmsg);
exit(1);
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/39758/showart_343494.html |
|