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

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值