Linux高级编程——匿名管道实现父子进程间通信 4. 编写程序实现以下功能: 利用匿名管道实现父子进程间通信,要求 父进程发送字符串“hello child”给子进程; 子进程收到父进程发送的数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hello_wordmy/article/details/88973011

4. 编写程序实现以下功能:
利用匿名管道实现父子进程间通信,要求
父进程发送字符串“hello child”给子进程;
子进程收到父进程发送的数据后,给父进程回复“hello farther”;
父子进程通信完毕,父进程依次打印子进程的退出状态以及子进程的pid。

代码如下:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#define size 256
int main(void)
{
    int fd[2],fds[2];
    char buf[size];
    pid_t pid,pr;
    int len,status;
    if(pipe(fd)<0)
    {
        perror("failed to pipe");
        exit(1);
    }
    if(pipe(fds)<0)
    {
        perror("failed to pipe");
        exit(1);
    }
    if((pid=fork())<0)
    {
        perror("failed to fork");
        exit(1);    
    }
    else if(pid>0)
    {
        char *str="hello child\n";
        char strs[50];
        printf("This is farther,write to fd[1]\n",fd[0],fd[1]);
        close(fd[0]);
        close(fds[1]);
        write(fd[1],str,strlen(str));
        read(fds[0],strs,50);
        printf("%s\n",strs);
        pr=waitpid(pid,&status,WUNTRACED);
        
        exit(0);
    }
    else
    {
        char *strs="hello father\n";
        printf("This is child,read from fd[0]\n");
        close(fd[1]);
        close(fds[0]);
        read(fd[0],buf,size);
        printf("%s\n",buf);
        write(fds[1],strs,strlen(strs));
        exit(0);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hello_wordmy/article/details/88973011