• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Linux C编程 – 管道pipe

php 搞代码 4年前 (2022-01-04) 31次浏览 已收录 0个评论

在linux中,管道也是一种文件,只不过比较特殊,我们可以用pipe函数创建一个管道,其原型声明如下:

#inlcude <unistd.h>

int pipe(int fields[2]);

其实它相当于一个通信缓冲区,fields[0]用来读,fields[1]用来写。下面的例子中,创建一个管道作为通信缓冲区,父进程创建了一个子进程,子进程通过管道的fields[1]描述符想管道中写入一个字符串,而父进程则利用管道的fields[0] 从管道中读取这个字串来源gao@daima#com搞(%代@#码网并显示出来:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>

#define BUF_SIZ 255 // message buffer size

int main(int argc, char **argv)
{
char buffer[BUF_SIZ + 1];
int fd[2];

// receive a string as parameter
if ( argc != 2)
{
fprintf(stderr, "Usage: %s string\n\a", argv[0]);
exit(1);
}

// create pipe for communication
if ( pipe(fd) != 0 )
{
fprintf(stderr, "Create pipe error: %s\n\a", strerror(errno));
exit(1);
}

if ( fork() == 0 ) // in child process write msg to pipe
{
close(fd[0]);
printf("Child %ld write to pipe\n\a", getpid());
snprintf(buffer, BUF_SIZ, "%s", argv[1]);
write(fd[1], buffer, strlen(buffer));
printf("Child %ld quit.\n\a", getpid());
}
else // in parent process, read msg from pipe
{
close(fd[1]);
printf("Parent %ld read from pipe\n\a", getpid());
memset(buffer, '\0', BUF_SIZ + 1);
read(fd[0], buffer, BUF_SIZ);
printf("Parent %ld read : \n%s\n", getpid(), buffer);
exit(1);
}
return 0;
}


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Linux C编程 – 管道pipe

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址