写一个程序,包含两个进程,在子进程输入参与计算的数据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()读出数据