hmchzb19 发表于 2016-09-01 21:25

请帮我看个popen,pclose的报错

我看了这里的代码,错的离谱的很啊
http://crasseux.com/books/ctutorial/Programming-with-pipes.html#Programming%20with%20pipes

SYNOPSIS
       #include <stdio.h>

       ssize_t getline(char **lineptr, size_t *n, FILE *stream);

       ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);
getdelim 的原型第三个参数是int, 这里面怎么能用 "\n\n" 2个换行做分割。

我改了下这个代码,还是不对,关键是我还不知道错在哪里,请大家指点下。

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

int main()
{
    FILE *ps_pipe;
    FILE *grep_pipe;

    size_t bytes_read;
    size_t nbytes=100;
    char *my_string;

    //open our two pipes
    ps_pipe=popen("ps -A","r");
    grep_pipe=popen("grep init","w");

    //check that pipes are non-null,therefore open
    if((!ps_pipe) || (!grep_pipe)){
      fprintf(stderr,"One or both pipes failed.\n");
      return EXIT_FAILURE;
      }

    //read from ps_pipe until two newlines
    my_string=(char *)malloc(nbytes+1);
    bytes_read=getline(&my_string,&nbytes,ps_pipe);
   
    int errno;
    //closing ps_pipe,checking for errors
    if(pclose(ps_pipe)!=0){
      perror("Could not run 'ps', or other error.\n");
      }

    //send output of 'ps -A' to 'grep init' with two newlines
    fprintf(grep_pipe, "%s\n",my_string);
   
    int ret;
    char error;
    //close grep_pipe,checking for errors
    if((ret=pclose(grep_pipe))!=0){
      printf("ret is %d",ret);
      perror("pclose()");
      printf("the pclose errored with %s",strerror(ret));
      }

    return 0;
    }
现在运行报错是这个
pclose(): Success
ret is 256the pclose errored with Unknown error 256

页: [1]
查看完整版本: 请帮我看个popen,pclose的报错