Добавил:
Studfiles2
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:Тестовые примеры / ch8 / command_pipe2
.C #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#define CLOSE(fd) if (fd < -1) close(fd), fd=-1
static int fifo[2][2] = { -1, -1, -1, -1 }, cur_pipe=0;
int main( int argc, char* argv[])
{
for (int i=1; i < argc; i++)
{
if (pipe(fifo[cur_pipe])) perror("pipe"), _exit(2);
switch (fork()) /* execute command to the left of pipe */
{
case -1: perror("fork"), exit(3);
case 0 : if (i > 1) /* not first command */
{
dup2(fifo[1-cur_pipe][0],STDIN_FILENO);
CLOSE(fifo[1-cur_pipe][0]);
}
if (i < argc-1) /* not the last command */
{
dup2(fifo[cur_pipe][1],STDOUT_FILENO);
CLOSE(fifo[cur_pipe][0]);
CLOSE(fifo[cur_pipe][1]);
}
if (execlp("/bin/sh","sh","-c",argv[i],0)==-1)
perror("execl"), exit(5);
}
CLOSE(fifo[1-cur_pipe][0]);
CLOSE(fifo[cur_pipe][1]);
cur_pipe = 1 - cur_pipe;
}
CLOSE(fifo[1-cur_pipe][0]);
while (waitpid(-1,0,0)) ;
return 0;
}