Linux无名管道pipe的使用(父子进程)
作者:互联网
我们来看一下pipe()函数的使用.
我构思了一个简单的父子进程通信函数,以帮助大家初步学习对无名管道pipe的操作 ,程序源代码如下.
#include<stdio.h>
#include<unistd.h>
#include<string.h>
void process_communication()
{
int fd[2];
int t1;
char string[] = "Hello my pipe!";
char buf_Read[60];
int nbytes;
int n;
int p = pipe(fd);
t1 = fork();
if(t1 > 0)//father
{
//read
waitpid(t1, NULL, 0);//等待其子进程结束后再往下执行, 确保无名管道内已经写入内容(子进程负责写)
nbytes = read(fd[0], buf_Read, sizeof(string));
if(nbytes > 0)
{
puts("Reading is successful.\n");
printf("%d\n",nbytes);
}
else
puts("reading error.\n");
}
else if(t1 == 0)//son
{
//write
n = write(fd[1], string, sizeof(string));
if(n > 0)
puts("Writing is suceessful.\n");
else
puts("writing error.\n");
}
else
{
puts("failure to generate a son process.\n");
}
return ;
}
int main()
{
process_communication();
return 0;
}
运行结果:
标签:string,puts,int,无名,pipe,else,Linux,t1 来源: https://blog.csdn.net/weixin_42048463/article/details/94736747