| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 891 人关注过本帖
标题:利用Pipe从父进程传递主函数参数到子进程并打印出来,有错误请教大家
只看楼主 加入收藏
read_write
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2016-6-7
收藏
 问题点数:0 回复次数:0 
利用Pipe从父进程传递主函数参数到子进程并打印出来,有错误请教大家
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/types.h>
int main(int argc,char *argv[])
{
  int fd[2],r,i;// fd[2]是pipe的文件描述符数组,r, i 定义的int变量
  if(pipe(fd)<0){
    perror("pipe");
    exit(0);
  } //创建管道
  char buf[1024];//buf字符串数组
  pid_t pid;//进程ID
  pid=fork();// 产生子进程和父进程
  if(pid<0){
  perror("fork");//pid<0 说明fork失败
  exit(0);
  }
  else if(pid>0){
    //这是父进程
    close(fd[0]);//关闭子进程用来读取的管道端口
    for(i=1;i!=argc;++i)
      write(fd[1],argv[i],strlen(argv[i])+1); //把主函数参数写到pipe的写管道fd[1]去
    close(fd[1]);//关闭写管道端口
  }
  else{
   //这是子进程
    close(fd[1]);//关闭写管道
    while(1){
      r=read(fd[0],buf,sizeof(buf));//从读管道中读取字符串到buf中
      if(r<=0)  //如果read函数返回值r《=0说明读写错误,则返回
        break;
      puts(buf);
    }
    close(fd[0]); //关闭读管道
  }
  return 0;
}
测试结果: ./test hello
 输出: hello
//这组结果是对的。
测试2: ./test hello world
输出:hello
//world 没法打出。
编译环境Linux
谢谢!
搜索更多相关主题的帖子: include 字符串 管道 
2016-06-07 12:13
快速回复:利用Pipe从父进程传递主函数参数到子进程并打印出来,有错误请教大家
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.014498 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved