:Linux之匿名管道

来源:百度文库 编辑:九乡新闻网 时间:2024/05/01 14:30:22
#include
#include
#include
#include

#define MAX_LINE 80
int main()
{
    int thePipe[2],ret;
    char buf[MAX_LINE+1];
    const char *testbuf="a test string.";
    if(pipe(thePipe)==0) {
        if(fork()==0) {
        close(thePipe[1]);
        sleep(3);
        ret=read(thePipe[0],buf,MAX_LINE);
        buf[ret]=0;
        printf("Child read %s\n",buf);
        close(thePipe[0]);
        exit(1);
        } else
        if(fork()==0) {
            close(thePipe[0]);
            ret=write(thePipe[1],testbuf,strlen(testbuf));
            printf("父进程写管道成功!\n");
            close(thePipe[1]);
            printf("父进程关闭写管道成功!\n");
            sleep(3);
        }
    }
    return 0;
}