免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1006 | 回复: 0

[C] 请帮我看个popen,pclose的报错 [复制链接]

论坛徽章:
13
CU大牛徽章
日期:2013-03-14 14:14:082016科比退役纪念章
日期:2016-07-22 11:15:35数据库技术版块每日发帖之星
日期:2016-05-27 06:20:002015亚冠之吉达阿赫利
日期:2015-08-05 10:06:542015年亚洲杯之韩国
日期:2015-04-01 16:05:42双鱼座
日期:2014-11-13 11:04:24丑牛
日期:2014-07-25 17:29:54子鼠
日期:2014-04-25 12:25:45丑牛
日期:2014-04-17 08:35:48巨蟹座
日期:2014-04-16 16:50:05CU大牛徽章
日期:2013-03-14 14:14:29CU大牛徽章
日期:2013-03-14 14:14:26
发表于 2016-09-01 21:25 |显示全部楼层
我看了这里的代码,错的离谱的很啊
http://crasseux.com/books/ctutorial/Programming-with-pipes.html#Programming%20with%20pipes

  1. SYNOPSIS
  2.        #include <stdio.h>

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

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

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

  1. #define _GNU_SOURCE
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <errno.h>
  5. #include <string.h>

  6. int main()
  7. {
  8.     FILE *ps_pipe;
  9.     FILE *grep_pipe;

  10.     size_t bytes_read;
  11.     size_t nbytes=100;
  12.     char *my_string;

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

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

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

  30.     //send output of 'ps -A' to 'grep init' with two newlines
  31.     fprintf(grep_pipe, "%s\n",my_string);
  32.    
  33.     int ret;
  34.     char error[100];
  35.     //close grep_pipe,checking for errors
  36.     if((ret=pclose(grep_pipe))!=0){
  37.         printf("ret is %d",ret);
  38.         perror("pclose()");
  39.         printf("the pclose errored with %s",strerror(ret));
  40.         }

  41.     return 0;
  42.     }
复制代码
现在运行报错是这个
  1. pclose(): Success
  2. ret is 256the pclose errored with Unknown error 256
复制代码


您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP