#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
int main()
{
int pipe_fd[2], read_bytes, i = 0;
pid_t pid;
char string[100];
char buf[100];
printf("Please input string:");
scanf("%s",string);
//创建无名管道
if(pipe(pipe_fd) < 0)
{
printf("pipe create error!\n");
exit(1);
}
//创建子进程 同时继承管道
if((pid = fork()) > 0)
{
close(pipe_fd[1]);
if((read_bytes = read(pipe_fd[0],buf,sizeof(string))) > 0)
{
printf("this is parent progress,after change string is %s\n",buf);
}
close(pipe_fd[0]);
waitpid(pid,NULL,0);
}
else if(pid == 0)
{
close(pipe_fd[0]);
while(string[i] != '\0')
{
string[i] = string[i] - 32;
i++;
}
if(write(pipe_fd[1],string,sizeof(string)) < 0)
{
printf("write error");
exit(1);
}
close(pipe_fd[1]);
_exit(0);
}
else
{
printf("fork error!\n");
exit(1);
}
}
运行结果
总结:
相关函数
pipe()
原型:int pipe(int filedes[2])
所需头文件#include<unistd.h>
返回值:成功,返回0,否则返回-1。参数数组包含pipe使用的两个文件的描述符。fd[0]:读管道,fd[1]:写管道。
在fork()前调用pipe(),否则子进程不会继承文件描述符。
fork()
原型:pid_t fork(void)
fork 调用一次返回两次
返回父进程的是创建子进程的pid
返回子进程的是0
read()
原型:ssize_t read(int fd, void *buf, size_t count)
功能描述: 从文件读取数据。
所需头文件: #include <unistd.h>)
参数:
fd: 将要读取数据的文件描述词。
buf:指缓冲区,即读取的数据会被放到这个缓冲区中去。
count: 表示调用一次read操作,应该读多少数量的字符。
返回值:返回所读取的字节数;0(读到EOF);-1(出错)。
write()
原型:ssize_t write(int fd,const void*buf,size_t count);
参数:
fd:是文件描述符
buf:通常是一个字符串,需要写入的字符串
count:是每次写入的字节数
返回值:
成功:返回写入的字节数
失败:返回-1并设置errno
ps: 写常规文件时,write的返回值通常等于请求写的字节
数count, 而向终端设备或者网络写时则不一定