Linux C 父子进程 与 有名管道

1、mkfifo() 函数 创建管道文件的节点


2、open()函数 在内核创建管道空间,库<fcntl.h>

       read()

       write()


3、fork() 函数 父子进程,库<sys/types.h>


代码 - - mkfifo()创建管道文件节点

  1 #include <stdio.h>
  2 
  3 int main()
  4 {
  5         int ret;
  6         //管道文件、字符设备、块设备、套接字 只有文件节点,不占磁盘空间
  7         ret = mkfifo("./myfifo",0777);  //mkfifo()只是创建了管道文件节点,并没有在内核空间创建管道空间
  8         //mkfifo()创建管道节点;open()在内核创建管道空间
  9         if(ret < 0)
 10         {
 11                 printf("myfifo create failure.\n");
 12                 return -1;
 13         }
 14 
 15         printf("myfifo create success.\n");
 16         return 0;
 17 }


代码 - - open()在内核创建管道空间

  1 #include <stdio.h>
  2 #include <sys/types.h>  //fork()
  3 #include <fcntl.h>      //open()、write()、read()
  4 
  5 int main()
  6 {
  7         pid_t pid;      //进程号
  8         int process_inter = 0;
  9         int process_inter_bak = 0;
 10 
 11         pid = fork();   //创建父子进程
 12         if(pid == 0)    //子进程        
 13         {
 14                 int i = 0;
 15                 int fd2;
 16                 fd2 = open("./myfifo",O_RDONLY);        //在内核创建管道空间
 17                 read(fd2, &process_inter_bak, 4);       //读取管道
 18                 close(fd2);
 19                 while(process_inter_bak == 0);
 20                 for(i = 0; i < 5; i++)
 21                 {
 22                         printf("this is child process i = %d\n",i);
 23                         usleep(100);
 24                 }
 25         }
 26         if(pid > 0)     //父进程
 27         {
 28                 int i = 0;
 29                 int fd1;
 30                 for(i = 0; i < 5; i++)
 31                 {
 32                         printf("parent process i = %d\n",i);
 33                         usleep(100);
 34                 }
 35                 process_inter = 1;
 36                 fd1 = open("./myfifo",O_WRONLY);
 37                 write(fd1, &process_inter, sizeof(process_inter));      //写入管道
 38                 while(1);
 39                 close(fd1);
 40         }
 41 
 42         return 0;
 43 }

执行:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值