#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
//int pipe(int pipefd[2]); //无名管道函数
//ssize_t write(int fd, const void *buf, size_t count);//写操作
//size_t read(int fd, void *buf, size_t count);//读操作
int main()
{
int pipe_fd[2] = {0};//对管道进行 读写的fd定义;
int status =0;
char *buf = "this is from father!";
char *readBuf;
pipe(pipe_fd);//创建管道
int pid;
pid = fork();//创建进程,无名管道只能用于父子进程中,其他进程不得使用
if(pid > 0)
{
close(pipe_fd[0]); //fd[0]是读操作,在进行写操作的时候一定要关闭读操作。
write(pipe_fd[1],buf,strlen(buf));
printf("this is a father !\n");
wait(&status);
printf("%d\n",WEXITSTATUS(status)); // 宏定义 WEXITSTATUS 把从child中的exit() 解析出来。
}else if(pid ==0){
readBuf = (char *)malloc(sizeof(char)*strlen(buf));
close(pipe_fd[1]);
read(pipe_fd[0],readBuf,strlen(buf));
printf("read : %s\n",readBuf);
printf("this is a child !\n");
exit(0);
}else{
printf("fork error! \n");
}
return 0;
}
其中主要运用到几个API
1.创建管道 :int pipe(int pipefd[2]);
2.创建进程:pid = fork();
3.进行写操作:size_t read(int fd, void *buf, size_t count);
4.进行读操作:ssize_t write(int fd, const void *buf, size_t count)
5.在father进程的中进行wait(*),然后再使用WEXITSTATUS(status),解析出child中的exit返回的值。