/*************本程序用于进程间的管道通信*****************/ #include #include #include int pid1,pid2; main() { int fd[2]; char OutPipe[100],InPipe[100]; pipe(fd); /*创建管道 */ while((pid1 = fork()) == -1); if(pid1 == 0) /*子进程1执行管道写操作 */ { lockf(fd[1],1,0); /*锁定管道 */ /*****给OutPipe数组赋值******/ sprintf(OutPipe,"Child process 1 is sending message!/n"); write(fd[1],OutPipe,50); /*向管道中写入数据 */ sleep(5); lockf(fd[1],0,0); /*管道解锁*/ exit(0); } else { while((pid2 = fork()) == -1); if(pid2 == 0) /*子进程2执行管道写操作 */ { lockf(fd[1],1,0); /*锁定管道 */ sprintf(OutPipe,"Child process 2 is sending message!/n"); write(fd[1],OutPipe,50); /*向管道中写入数据 */ sleep(5); lockf(fd[1],0,0); /*管道解锁*/ exit(0); } else /*父进程执行管道读操作*/ { wait(0); /*等待子进程1结束*/ read(fd[0],InPipe,50); /*从管道中读出数据*/ printf("%s/n",InPipe); wait(0); /*等待子进程2结束*/ read(fd[0],InPipe,50); /*从管道中读出数据*/ printf("%s/n",InPipe); exit(0); } } } |