找回密码
 用户注册

QQ登录

只需一步,快速开始

查看: 3423|回复: 0

linux下的C语言开发(管道通信)

[复制链接]
发表于 2012-2-3 13:24:28 | 显示全部楼层 |阅读模式
【 声明:版权所有,欢迎转载,请勿用于商业用途。  联系信箱:feixiaoxing @163.com】

    Linux系统本身为进程间通信提供了很多的方式,比如说管道、共享内存、socket通信等。管道的使用十分简单,在创建了匿名管道之后,我们只需要从一个管道发送数据,再从另外一个管道接受数据即可。#include <stdio.h>
  1. #include <unistd.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. int pipe_default[2];  
  5. int main()
  6. {
  7.     pid_t pid;
  8.     char buffer[32];
  9.     memset(buffer, 0, 32);
  10.     if(pipe(pipe_default) < 0)
  11.     {
  12.         printf("Failed to create pipe!\n");
  13.         return 0;
  14.     }
  15.     if(0 == (pid = fork()))
  16.     {
  17.         close(pipe_default[1]);
  18.         sleep(5);
  19.         if(read(pipe_default[0], buffer, 32) > 0)
  20.         {
  21.             printf("Receive data from server, %s!\n", buffer);
  22.         }
  23.         close(pipe_default[0]);
  24.     }
  25.     else
  26.     {
  27.         close(pipe_default[0]);
  28.         if(-1 != write(pipe_default[1], "hello", strlen("hello")))
  29.         {
  30.             printf("Send data to client, hello!\n");
  31.         }
  32.         close(pipe_default[1]);
  33.         waitpid(pid, NULL, 0);
  34.     }
  35.     return 1;
  36. }
复制代码
    下面我们就可以开始编译运行了,老规矩分成两步骤进行:(1)输入gcc pipe.c -o pipe;(2)然后输入./pipe,过一会儿你就可以看到下面的打印了。
[test@localhost pipe]$ ./pipeSend data to client, hello!Receive data from server, hello!

作者:feixiaoxing 发表于2012-2-2 20:01:43 原文链接

您需要登录后才可以回帖 登录 | 用户注册

本版积分规则

Archiver|手机版|小黑屋|ACE Developer ( 京ICP备06055248号 )

GMT+8, 2024-4-30 00:35 , Processed in 0.011210 second(s), 6 queries , Redis On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表