阅 读 文 章

Linux 编程之C与脚本的混合编程

[来源:网上转载 (http://www.chinaunix.net) | 作者:网友(不详) | 时间:2007-07-07 | 浏览:人次 ]

  调用完以后,buf中的数据就是 “male”了,怎么样,还算方便吧?

  以上只是用结合脚本完成了一个比较简单的任务,所以我没有把这些脚本单独形成脚本文件。如果你善于使用 perl、shell、awk,那么可以写出更强大的脚本文件来处理更复杂的问题,然后通过类似 my_system( )的方法,在 c/c 等其它语言中取得脚本的输出结果,实现有趣的“混合编程”。

  希望你能从中得到乐趣!

  #include

  #include

  #include

  #include

  #include

  static int my_system(const char* pCmd, char* pResult, int size)

  {

  int fd[2];

  int pid;

  int count;

  int left;

  char* p = 0;

  int maxlen = size – 1;

  memset(pResult, 0, size);

  if(pipe(fd))

  {

  printf("pipe error\n");

  return –1;

  }

  if((pid = fork()) == 0)

  {// chile process

  int fd2[2];

  if(pipe(fd2))

  {

  printf("pipe2 error\n");

  return –1;

  }

  close(1);

  dup2(fd2[1],1);

  close(fd[0]);

  close(fd2[1]);

  system(pCmd);

  read(fd2[0], pResult, maxlen);

  pResult[strlen(pResult)-1] = 0;

  write(fd[1], pResult, strlen(pResult));

  close(fd2[0]);

  exit(0);

  }

  // parent process

  close(fd[1]);

  p = pResult;

  left = maxlen;

  while((count = read(fd[0], p, left))) {

  p = count;

  left -= count;

  if(left == 0)

  break;

  }

  close(fd[0]);

  return 0;

  }

  int main(void)

  {

  char result[1025];

  my_system("/sbin/ifconfig", result, 1025);

  printf("the result is\n\n%s\n", result);

  return 0;

  }

论坛热门帖子: [lch203] 写得蛮好的linux学习笔记(10-21)
[黑马制造] 学习java的30个目标(10-19)
[笑傲股林] 做测试半年了,有点迷茫,应该再学些什么提高自己的测试水平和测试能力呢?(10-19)
[udp8589] 大家用google的来吱一声? 用百度的~~也来报道下?(10-18)
[沂偌掳兆] 本人总结的一些认为C++比较经典的书籍,希望对大家有用(10-18)
TAG标签: 编程 混合 脚本 user.conf 我们 int pResult awk 数据

最新评论 共有0位网友发表了评论

发表评论

评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名:(注册)
密码:
验证码:
匿名发表

网站地图友情连接交流论坛网站投稿广告服务联系我们留言本站长统计
Some rights reserved: www.chmhome.com, 鄂ICP备07010232号 E-mail:chinakafei@live.com,QQ:552766
中国咖啡技术网(Chmhome):国外编程技术书籍,中文编程手册,经典编程文章,交流技术,技术软件下载,计算机论文,毕业论文.