进程间通信(一) :管道

一,用管道进行父子进程通信

代码:

#include<unistd.h>
#include<stdio.h>

#define MAXLINE 120
#define MSGINFO "hurry up !\n"

int main(void)
{
int fd[2];
int result;
char msg[MAXLINE+1]={'\0'};
pid_t pid;
if(pipe(fd)<0)
{
printf("create pipe failed !");
}


if((pid=fork())<0)
{
printf("fork child proc failed!\n");
}


if(pid > 0)  //father
{
//close(fd[0]);
if(dup2(fd[1], STDOUT_FILENO)<0)
{
printf("dup2 error !\n");
}


write(STDOUT_FILENO, MSGINFO, strlen(MSGINFO));
}
else  //chilld
{
//close(fd[1]);
if(dup2(fd[0], STDIN_FILENO) < 0)
{
printf("dup2 error in child proc !");
}


read(STDIN_FILENO, msg, MAXLINE);
printf("get msg:%s \n", msg);
}
return 0;
}

执行结果:

get msg:hurry up !


二,popen和pcloseh函数

     popen启动一个shell进程,并执行输入的命令,把执行结果通过FILE输出

代码:

#include<unistd.h>
#include<stdio.h>

#define MAXLINE 120

int main(void)
{
char text[MAXLINE]={'\0'};
FILE *fin;


   if((fin = popen("more /tmp/text.txt", "r"))<0)
    {
    printf("error in popen !\n");
    }


  while(1)
   {
       if(fgets(text, MAXLINE, fin) == NULL)
         {
       break;
         }


      fputs(">>", stdout);
      fputs(text, stdout);
   }
   if(pclose(fin) == -1)
   {
  printf("pclose err !");
   }
return 0;
}

执行结果:

>>how areyou ?
>>fine,and you?
>>fine too.
>>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值