Linux无名管道pipe的使用(父子进程)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Linux无名管道pipe的使用(父子进程),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1096字,纯文字阅读大概需要2分钟。
内容图文
我们来看一下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;
}
运行结果:
内容总结
以上是互联网集市为您收集整理的Linux无名管道pipe的使用(父子进程)全部内容,希望文章能够帮你解决Linux无名管道pipe的使用(父子进程)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。