Linux 基于fork()函数父子进程之间的通信

写一个程序,包含两个进程,在子进程输入参与计算的数据a、b的值,在父进程中计算a+b的值并输出计算结果;要求输出子进程和父进程的进程ID.

源程序:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <wait.h>
#include <unistd.h>
int main(void) {
pid_t pid;
int fd[2];
int ret =pipe(fd);
if (ret < 0) {
perror("failed to pipe\n");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid < 0) {
perror("failed to fork\n");
exit(EXIT_FAILURE);
} 
else if (pid == 0) {
printf("pid = %d, parent pid = %d\n", getpid(), getppid());
printf("input a and b\n");
int a, b;
scanf("%d%d",&a,&b);
write(fd[1], &a, sizeof(int));
write(fd[1], &b, sizeof(int));
} 
else{
int a, b;
read(fd[0], &a, sizeof(int));
read(fd[0], &b, sizeof(int));
printf("a+b=%d\n",a+b);
wait(NULL);
close(fd[0]);
close(fd[1]);
}
exit(EXIT_SUCCESS);
}

结果分析:
由于父子进程的数据是不共享的,上述代码使用管道实现了父子进程的通信,管道是一种把两个进程之间的标准输入和标准输出连接起来的机制,从而提供一种让多个进程间通信的方法,当进程创建管道时,每次都需要提供两个文件描述符来操作管道。其中一个对管道进行写操作,另一个对管道进行读操作。对管道的读写与一般的IO系统函数一致,使用write()函数写入数据,使用read()读出数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值