Linux API fork 子进程 创建 & 无名管道通信

#include<unistd.h>
#include<stdio.h>

int main()
{
    
    int filedes[2];
    
    char buffer[80];
    
    pipe(filedes);
    
    printf("my pid is %u.\r\n",getpid());
    
    /* 实测发现,子进程不会输出上面这句话,表示子进程从这开始的 */
    if( fork() > 0 )
    {/* 父进程运行 */
        
        /* 对于父进程:fork()返回子进程的PID */
        /* 对于子进程:fork()返回0 */
        
        char s[] = "hello,world!\r\n";
        
        sleep(5);
        
        write(filedes[1],s,sizeof(s));
        
    }
    else
    {/* 子进程运行 */

      
    /* 实测:read 会进行阻塞,直到数据读取完成 */ read(filedes[0],buffer,sizeof(buffer)); printf("%s",buffer); } while(1) { sleep(1); } }

 

posted on 2018-04-02 16:24  所长  阅读(199)  评论(0编辑  收藏  举报

导航