C程序使用管道gziping Ubuntu上的文件

时间:2015-11-29 10:17:14

标签: c ubuntu pipe fork gzip

我正在尝试编写一个c程序来实现对Ubuntu的以下表述:

file | gzip newfile.gz

所以我阅读了beej的指南并尝试了以下代码:

int pfds[2];
char buffer[256];
pipe(pfds);
pid_t t=fork();
if (!t) {
    int bytesin;
    close(1);       /* close normal stdout */
    dup(pfds[1]);   /* make stdout same as pfds[1] */
    close(pfds[0]); /* we don't need this */
    int fd = open("1",O_RDONLY);
    while (bytesin = read(fd,buffer,256) !=0){
        write(pfds[1],buffer,strlen(buffer));
    }

} else {
    waitpid(t,NULL,0);
    bzero(buffer,256);
    close(0);       /* close normal stdin */
    dup(pfds[0]);   /* make stdin same as pfds[0] */
    close(pfds[1]); /* we don't need this */
    execlp("gzip","myfile.gz", NULL);
}

return 0;

好吧,我读好文件,然后通过管道获取内容。但是,当我尝试执行gzip时,出现以下错误:

compressed data not written to a terminal

帮助将不胜感激!

0 个答案:

没有答案