Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C/C++: Программирование под Unix/Linux > pipes


Автор: Ak47black 21.9.2010, 13:56
Здравствуйте.
Помогите пожалуйста найти ошибку в коде
Код

#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <netinet/in.h>
#include <resolv.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
/*
 *
 */
int main (int argv, char** argc)
{
    int pfildes[2];
    pid_t pid;
 
    if (pipe(pfildes) == -1)    {perror("error creating pipe"); exit(1);}
    if ((pid = fork()) == -1)   {perror("error creating child process"); exit(1);}
    else if (pid == 0) {        /* child:                      */
          close(pfildes[0]);    /* close read end of pipe               */
          dup2(pfildes[1], 1);   /* make 1 same as write-to end of pipe  */
          close(pfildes[1]);    /* close excess fildes                  */
          execlp("ls", "-1", NULL);
          perror("error executing child process");       /* still around?  exec failed           */
          _exit(1);             /* no flush                             */
        }
    else {                      /* parent:               */
          int status;
          waitpid(pid, &status, 0);
          if (WIFEXITED(status))
          {
              printf("[ls] executed ok");
          }
          else
          {
              perror("error executing child process");
          }
          close(pfildes[1]);    /* close write end of pipe              */
          dup2(pfildes[0],0);   /* make 0 same as read-from end of pipe */
          close(pfildes[0]);    /* close excess fildes                  */
          execlp("cut", "-c", "44-56", NULL);
          perror("error executing child process");       /* still around?  exec failed           */
          exit(1);            
        }

}

Хочу запустить этим кодом вот такую сложную команду
Цитата

ls -l | cut -c 44-56

пробую запустить, но получаю
Цитата

-c: you must specify a list of bytes, characters, or fields
Try `-c --help' for more information.

Автор: Sartorius 21.9.2010, 14:02
Возможно так ?
Код

execlp("cut", "-c 44-56", NULL);

Автор: Ak47black 21.9.2010, 14:05
тоже самое
Цитата

-c: you must specify a list of bytes, characters, or fields
Try `-c --help' for more information.

Автор: Void 21.9.2010, 15:54
Код
execlp("cat", "cat", "-c", "44-56", NULL);

Аналогичная ошибка для ls. argv[0] кто предоставлять будет?

Автор: Ak47black 21.9.2010, 17:00
Подправил, теперь работает без ошибок, но выдаёт просто пустое n-е количество строк, а если просто набрать в консоле 
Цитата

ls -l | cut -c 44-56

то нетак.
Может тут опять что-то из-за директории?

Автор: Void 21.9.2010, 17:15
Вызов ls поправил? Всё должно работать.
Кстати, ждать (waitpid) завершения ls перед запуском cut нельзя. Если вывод ls будет больше, чем PIPE_BUF, то дочерний процесс заблокируется при записи в трубу и будет deadlock.

Автор: Ak47black 21.9.2010, 17:42
Вроде-бы как всё должно быть
Код

    int pfildes[2];
    pid_t pid;
 
    if (pipe(pfildes) == -1)    {perror("error creating pipe"); exit(1);}
    if ((pid = fork()) == -1)   {perror("error creating child process"); exit(1);}
    else if (pid == 0) {        /* child:                      */
          close(pfildes[0]);    /* close read end of pipe               */
          dup2(pfildes[1], 1);   /* make 1 same as write-to end of pipe  */
          close(pfildes[1]);    /* close excess fildes                  */
          execlp("ls", "ls", "-1", NULL);
          perror("error executing child process");       /* still around?  exec failed           */
          _exit(1);             /* no flush                             */
        }
    else {                      /* parent:               */
          close(pfildes[1]);    /* close write end of pipe              */
          dup2(pfildes[0],0);   /* make 0 same as read-from end of pipe */
          close(pfildes[0]);    /* close excess fildes                  */
          execlp("cut", "cut", "-c", "44-56", NULL);
          perror("error executing child process");       /* still around?  exec failed           */
          exit(1);            
        }

но выдаёт пустые строки

Автор: Void 21.9.2010, 17:56
Код
execlp("ls", "ls", "-1", NULL);
//                 ^^^^ ы? ыгы.

Автор: Ak47black 21.9.2010, 18:01
Что?  smile  smile  smile 
Параметр, как параметр :|

Автор: Void 21.9.2010, 18:07
Единица у тебя там, а хотел -l небось smile

Автор: Ak47black 21.9.2010, 18:11
Аааааа, так вот оно в чём!  smile 
Кстати в этом, моём NetBeans'е в котором я кодю, l и 1 выглядят полностью одинаково  smile
Спасибо!

Добавлено через 4 минуты и 47 секунд
А на форуме
Код

1 l

Тоже l маскируется под 1

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)