进程间通信:无名管道

进程间通信:无名管道
无名管道(pipe)是一种半双工的进程间通信方式,只能用于有公共祖先的进程间通信. 通常一个进程创建一个管道后,fork出一个子进程,然后子进程中也可以使用pipe了.
定义一个管道: int fpipe[2];// 其中fpipe[0]是读, fpipe[1]是写.
创建管道: int pipe(fpipe);
简单例子如下:
#include

include

include

define MAXLINE 20

int main(void )
{
char line[MAXLINE];
//define the pipe
int fpipe[2];
if(pipe(fpipe)<0)
{
printf(“error taken place during creating the pipe! \n”);
return 1;
}
pid_t pid;
if ((pid = fork())< 0)
{
printf(“error taken place during creating fork()! \n”);
return 1;
}
else if(pid == 0 )
{
//in the child’s process
close(fpipe[0]);
//only write;
write(fpipe[1], “I’m the data!”, MAXLINE);
}
else
{
//in the parent process
sleep(2);
close(fpipe[1]);
//read
read(fpipe[0], line, MAXLINE);
printf(“pipe: %s \n”, line);
}
return 0;
}
pipe用于进程间同步:

include

include

include

define MAXLINE 200

int main(void )
{
char line[MAXLINE];
//define the pipe
int fpipe[2];
if(pipe(fpipe)<0)
{
printf(“error taken place during creating the pipe! \n”);
return 1;
}
pid_t pid;
if ((pid = fork())< 0)
{
printf(“error taken place during creating fork()! \n”);
return 1;
}
else if(pid == 0 )
{
//in the child’s process
close(fpipe[0]);
//only write;
write(fpipe[1], “c”, 1);
}
else
{
//in the parent process
close(fpipe[1]);
//read
char t = 0;
read(fpipe[0], &t, 1);
if(t == ‘c’)
{
printf(“process synchronization done! \n”);
}
else
{
printf(“error taken place!”);
}
}

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值