Linux C 学习日记(1)无名管道

子进程从父进程读取参数,以便于子进程执行execlp函数。
父进程把数据写入到 无名管道中 ,子进程从 无名管道 读取数据,并作为参数传到execlp函数中。
*无名管道必须在亲缘关系的进程中使用,当进程和程序结束之后,无名管道即刻被销毁


#include<unistd.h>
#include<stdio.h>
#include<string.h>
int main()
{
pid_t pid;
int pipefd[2];       //定义一个无名管道 读端 0  写端 1
char data[20];
pipe(pipefd);       //定义一个无名管道 
pid=fork();         //创建进程
if(pid==0)          //子进程
{
  printf("This is child process!\n");  
  close(pipefd[1]);          //关闭写端 1
  read(pipefd[0],data,20);         //从读端 0 里读取数据 存到 data 
  execlp("ls","-l",data,NULL);      //execlp 函数 显示当前目录下所有文件 
}
else if(pid>0)     //父进程
{
  printf("This is parent process!\n");
  close(pipefd[0]);                //关闭读端 0
  char string[20]="/work";
  write(pipefd[1],string,20);     //从 string 中读取数据到 写端 1
  wait(NULL);             //等待子进程结束,父进程再结束
}
return 0;
}

猜你喜欢

转载自blog.csdn.net/Black_goat/article/details/83656788