zoukankan      html  css  js  c++  java
  • Linux无名管道通信介绍

    Linux下无名管道一般仅用于父子进程间的通信;

    测试代码如下

    //file name: fifo_test.c
    #include <sys/prctl.h>
    #include "fifo_test.h"
    
    
    int 
    main(int argc, char **argv)
    {
    	int ret = 0;
    	char buf[32] = {''};
    	int pipe_fd[2]; //0---read 1--write
    	pid_t pid;
    	
    	if(pipe(pipe_fd)<0)
    	{
    		printf("pipe create error/n");
    		return -1;
    	}
    	if((pid=fork())==0)  //子进程
    	{	
    		close(pipe_fd[0]);
    		prctl(PR_SET_NAME, "child");
    		while(1)
    		{	
    			strcpy(buf, "hi, from child process!");
    			ret=write(pipe_fd[1],buf,sizeof(buf));
    			sleep(3);//
    		}
    	}
    
    	close(pipe_fd[1]);
    	while(1)
    	{
    		ret=read(pipe_fd[0],buf,sizeof(buf));
    		printf("father process, recv msg: %s
    ",buf);
    	}	
    
    	return 0;
    }
    

    编译

    gcc -c fifo_test.c -o fifo_test.o -Wall -g 
    gcc fifo_test.o  -o fifo_test -Wall -g 
    

    执行结果

    ./fifo_test 
    father process, recv msg: hi, from child process!, len: 32
    father process, recv msg: hi, from child process!, len: 32
    father process, recv msg: hi, from child process!, len: 32
  • 相关阅读:
    POJ3678 KATU PUZZLE
    poj3321(codevs1228)苹果树
    codevs 1955 光纤通信 USACO
    codevs 1027 姓名与ID
    codevs 1051 接龙游戏
    洛谷 P1717 钓鱼
    codevs 1062 路由选择
    洛谷 P1083 借教室
    codevs 2596 售货员的难题
    Vijos 1053 easy sssp
  • 原文地址:https://www.cnblogs.com/fensnote/p/13436454.html
Copyright © 2011-2022 走看看