将stdin(和存储值)管道读取到子节点,执行剪切并返回值

时间:2017-05-06 16:39:28

标签: c pipe fork dup

我正在做一个程序,它将接收3个参数,。/ a.out a b c,其中a和c是列号,b和操作数来自以下行分隔的行:。

当它真实再现stdin时没有结果。

示例:

$ ./a.out 1 > 2
$ 5:2:1:6
5:2:1:6

$ ./a.out 2 = 4
$ 1:2:3:4
$

我已经在我的第一个版本中尝试过,当切割要求时,管道和stdin读取,但我的问题是我丢失了输入。

现在我正在尝试从孩子内部的stdin读取,存储并通过管道传递它,但是对于我的测试我猜测execlp没有得到stdin输入。

我不能使用awk,它用于学术工作。

我的代码此刻:

int main(int argc, char const *argv[]){

    int n,f;
    char coluna1[16];
    char coluna2[16];
    char strin[PIPE_BUF];
    //put together args cut
    char buffer[PIPE_BUF];
    sprintf(buffer, "-f%s,%s",argv[1],argv[3]);

    //pipes
    int fd[2];
    int fd2[2];
    pipe(fd);
    pipe(fd2);

    if(!fork()) {
        close(fd[0]); //close read
        dup2(fd[1],1); //std output duplicated to pipe write
        close(fd2[0]); //close read
        //readline stdin
        n = read(0,strin,PIPE_BUF);
        write(fd2[1],strin,n);
        //cut -d: -f2,4 -
        execlp("cut","cut","-d:",buffer,"-",NULL);
    }
    //pai recebe do pipe
    close(fd[1]); //close write
    close(fd2[1]); //close write
    n = read(fd2[0],strin,PIPE_BUF); //read stdin from pipe
    f = read(fd[0],buffer,PIPE_BUF); //stdout from cut
    sscanf(buffer,"%[^:]:%s",coluna1,coluna2);

    //write the result from the cut to "bug check"
    write(1,buffer,f);

    //printfs just to check if everything worked
    if(strcmp(argv[2],"=")) if(atoi(coluna1) == atoi(coluna2)) { write(1,strin,n); printf("ACERTEI NO =\n"); }
    if(strcmp(argv[2],">=")) if(atoi(coluna1) >= atoi(coluna2)) { write(1,strin,n); printf("ACERTEI NO >=\n"); }
    if(strcmp(argv[2],"<=")) if(atoi(coluna1) <= atoi(coluna2)) { write(1,strin,n); printf("ACERTEI NO <=\n"); }
    if(strcmp(argv[2],">")) if(atoi(coluna1) > atoi(coluna2)) { write(1,strin,n); printf("ACERTEI NO >\n"); }
    if(strcmp(argv[2],"<")) if(atoi(coluna1) < atoi(coluna2)) { write(1,strin,n); printf("ACERTEI NO <\n"); }
    if(strcmp(argv[2],"!=")) if(atoi(coluna1) != atoi(coluna2)) { write(1,strin,n); printf("ACERTEI NO !=\n"); }

}

1 个答案:

答案 0 :(得分:0)

修正如下:

SELECT
   c.CustomerID
  ,sum(case when o.FiscalYear = '2016' then 1 else 0 end)  AS TotalOrders
FROM Customers c
LEFT JOIN Orders o
 ON c.CustomerID = o.CustomerID
GROUP BY c.CustomerID