使用dup2将内容从父级发送给子级

时间:2015-03-14 14:02:48

标签: pipe parent-child stdout stdin dup2

我要做的是将文本文件动态加载到缓冲区(在父级中)并将此数据传递给另一个进程(子级)。然后child将这些数据返回给父级。到目前为止,我已经做了这么多。有什么帮助吗?

string fileName;// File will be opened
char* str=argv[1];
fileSetup(argv[1]);//check if file exists and load into buffer
int pipe_fds[2]; //Define and create pipes
pid_t pid;//child process ID
int read_fd; //pipe_fds[0]
int write_fd;//pipe_fds[1]
int p=pipe (pipe_fds);
read_fd = pipe_fds[0]; 
write_fd = pipe_fds[1]; 
pid = fork ();//Fork the child process. 
if(pid == -1)//Check if pipe successfully created
{
   cerr << "Failed to fork" << endl;
   exit(1);
}
if(pid == 0)//Child
{               
    // Child process closes up input side of pipe 
    dup2 (write_fd, STDIN_FILENO);
    execlp ("./child", "child",str, NULL);//Run child process       
    close(read_fd);         
}
//STOPPED AT SENDING FILE DESCRIPTORS
else//Parent
{

}

1 个答案:

答案 0 :(得分:0)

使用两个管道会更好,否则会存在竞争条件。我没有看到任何理由在这里使用execlp。

 int prnt_chld[2],chld_prnt[2];
    pipe(prnt_chld) ;
    pipe(chld_prnt);
    char *buf ,*buf1;
    int data;
    // same as yours
    if(pid==0)
    {
    close(prnt_chld[1]); close(chld_prnt[0]);
    data=read(prnt_chld[0],buf,MAX); // MAX is the maximum you want to read
    close(prnt_chld[0]);
    buf[data]='\0';
    write(chld_prnt[1],buf,MAX);   
     close(chld_prnt[1]);
    }
    else
    {
    close(prnt_chld[0]); close(chld_prnt[1]);
    write(prnt_chld[1],buf,MAX);
    close(prnt_chld[1]);
    data=read(chld_prnt[0],buf1,MAX); 
    buf1[data]='\0';
     close(chld_prnt[0]);
    // Printing the Buffer1
    }