parents_child

来源:互联网 发布:网络摄像头改ip软件 编辑:程序博客网 时间:2024/06/06 06:34
#include <sys/types.h>#include <sys/wait.h>#include <unistd.h>#include <stdio.h>#include <stdlib.h>#include <string.h>int main(){int fd[2],pf[2];pid_t pid;char buf[10];int bytes_write,bytes_read;if( pipe(fd) < 0 || pipe(pf) < 0 ){perror("pipe error");exit(1);}pid = fork();if( pid > 0 ){close(fd[0]);close(pf[1]);strcpy(buf,"hello!");bytes_write = write(fd[1],buf,strlen(buf));if( -1 == bytes_write ){perror("write error");exit(1);}memset(buf,0,10);bytes_read = read(pf[0],buf,10);if( bytes_read == -1 ){perror("read error");exit(1);}buf[bytes_read] = '\0';printf(" buf is %s\n",buf);close(fd[1]);close(pf[0]);wait(NULL);exit(0);}else if( pid == 0 ){close(fd[1]);close(pf[0]);bytes_read = read(fd[0],buf,10);if( -1 == bytes_read ){perror("read1 error");exit(1);}bytes_write = write(pf[1],buf,bytes_read);if( -1 == bytes_write ){perror("write error");exit(1);}close(fd[0]);close(pf[1]);exit(0);}}


原创粉丝点击