pipe管道(fork)

#include <unistd.h>

int pipe(int fd[2]);

成功返回0,失败返回-1;

pipe函数用于创建管道,在数组中填上两个新的文件描述符后返回0;失败返回-1;

fd[0]为管道的读端,fd[1]为管道写端.

用法在下列代码中有解释

/*pipe函数用法1*/
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main() { int data_proc; int fd[2]; const char data[]="jey"; pid_t fork_result; char buffer[BUFSIZ+1]; memset(buffer,'\0',sizeof(BUFSIZ)); if(pipe(fd)==0) //创建pipe管道 { data_proc=write(fd[1],data,strlen(data)); //向管道写数据,pip[1]
printf(
"Wrote %d bytes.\n",data_proc); data_proc=read(fd[0],buffer,sizeof(buffer)); //从管道读数据,pip[0]
]
        printf("Read %d bytes:%s\n",data_proc,buffer);
        exit(0);
    }
    exit(0);
}

运行结果:

 

跨越fork调用的管道:

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

int main()
{
    int data_proc;
    int pips[2];
    const char data[]="jey";
    pid_t fork_result;
    char buffer[BUFSIZ+1];
    memset(buffer,'\0',sizeof(BUFSIZ));
    if(pipe(pips)==0)                   //创建pipe管道
    {
        fork_result=fork();
        if(fork_result==-1)
        {
            printf("fork error\n");
        }
        else if(fork_result==0)
        {
            data_proc=read(pips[0],buffer,BUFSIZ);  //子进程读管道中的数据,pips[0]为管道读端
            printf("read %d bytes:%s\n",data_proc,buffer);
            exit(0);
        }
        else if(fork_result>0)
        {
            data_proc=write(pips[1],data,strlen(data));  //父进程向管道写端写数据,pips[1]为管道写端
            printf("Wrote %d bytes.\n",data_proc);
        }
    }
    exit(0);
}

运行结果:

 

管道和exec函数

 

/* pip2.c */
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main() { int data_proc; int pips[2]; const char data[]="jey"; pid_t fork_result; char buffer[BUFSIZ+1]; memset(buffer,'\0',sizeof(BUFSIZ)); if(pipe(pips)==0) //创建pipe管道 { fork_result=fork(); if(fork_result==-1) { printf("fork error\n"); } else if(fork_result==0) { sprintf(buffer,"%d",pips[0]); (void)execl("pip3","pip3",buffer,(char*)0);//向pip3进程发送buffer数据(为pips[0],文件描述符) exit(0); } else if(fork_result>0) { data_proc=write(pips[1],data,strlen(data)); //父进程向管道写端写数据,pips[1]为管道写端 printf("%d - Wrote %d bytes.\n",getpid(),data_proc); } } exit(0); }


/*. pip3.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc,char* argv[])
{
int fd;
char buffer[BUFSIZ+1];
int data_proc;
memset(buffer,'\0',sizeof(buffer));
sscanf(argv[1],"%d",&fd);//将argv[1]中的字符串(pips[0])转换为int型并赋值给fd
data_proc=read(fd,buffer,BUFSIZ);//冲文件描述符指向的管道读数据到buffer中
printf("%d - read %d bytes:%s\n",getpid(),data_proc,buffer);
exit(0);
}
 

运行结果:

 

posted @ 2023-02-24 13:05  撒西不纳拉  阅读(110)  评论(0)    收藏  举报