1.什么是进程间通信?
进程是一个独立的资源分配单元,不同进程之间的资源是独立的,没有关联,不能在一个进程中直接访问另一个进程的资源。
然而,进程不是孤立的,不同的进程需要进行信息的交互和状态的传递登,因此需要进程间通信。
简言之,进程间通信是实现多进程配合工作的方式与手段。
2.进程间通信的功能包括什么?并简单描述。
- 数据传输:一个进程需要将它的数据发送给另一个进程。
- 资源共享:多个进程之间共享同样的资源。
- 通知事件:一个进程需要向一个或一组进程发送消息,通知它们发生了某种事件。
- 进程控制:有些进程希望完全控制另一个进程的执行,此时控制进程希望能够连接另一个进程的所有操作,并能够及时知道它的状态改变。
3.管道的(局限性)优缺点
优点:
- 管道存在于内存中,读写效率很高
- 简单易用,不需要复杂的编程实现
缺点:
- 半双工,数据在统一时刻只能在一个方向上流动
- 管道没有名字,只能在具有公共祖先的进程之间使用
- 管道的缓冲区是有限的,在Linux中,缓冲区大小固定为4KByte
- 管道所传诵的数据是无格式的,这要求管道的读出方与写入方必须事先约定好数据的格式
- 数据只能由一端写入,另一端读出
- 从管道读数据是一次性操作,数据一旦被读走,它就从管道中被抛弃,释放空间以便写更多数据。
4.利用dup函数实现标准输出重定向(重定向到一个文件中)
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
int main(){
int fd1, fd2;
char buf[] = "hello world";
fd1 = open("out", O_CREAT | O_WRONLY, 0777);
if(fd1 < 0){
perror("open");
exit(-1);
}
fd2 = dup2(fd1, 1);
printf("std output:%s\n", buf);
return 0;
}
运行截图:
5.编程实现无名管道通信,父进程向子进程发送字符串”hello world”
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(){
int fd_pipe[2];
char buf[] = "hello world";
pid_t pid;
if(pipe(fd_pipe)<0){
perror("pipe");
}
pid = fork();
if(pid < 0){
perror("fork");
exit(-1);
}
if(pid == 0){
close(fd_pipe[1]);
memset(buf, 0, sizeof(buf));
read(fd_pipe[0], buf, sizeof(buf));
printf("from parent: %s\n", buf);
}
else{
close(fd_pipe[0]);
write(fd_pipe[1], buf, sizeof(buf));
wait(NULL);
}
return 0;
}
运行截图: