1.为什么需要进程间通信?
每一个进程都拥有自己的独立的进程虚拟地址空间,具有独立性,有时了各个进程之间需要交互传输数据或者其他操作,需要进程通信。
2.进程通信有多少种方式
1.管道 2. 共享内存 3.消息队列 4.信号量 5.信号 6.套接字
3.管道介绍及代码实现
3.1无名管道
无名管道:用于有亲属间关系的进程间通信所使用
函数:int pipe(int pipefd[2]);
1.无名管道是单向流通的 ,(代码实现无名管道初探)
/*
parent process: write pipe
child process: read pipe
*/
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>int main(void)
{
int fd[2];
int pid;if(pipe(fd) == -1)
perror("pipe");pid = fork();
if(pid > 0) //parent process
{
close(fd[0]);
sleep(5);
write(fd[1], "ab", 2);while(1);
}
else if(pid == 0)
{
char ch[2];printf("Child process is waiting for data: \n");
close(fd[1]);
read(fd[0], ch, 2);
printf("Read from pipe: %s\n", ch);
}return 0;
}
2.无名管道容量有多少大
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <sys/wait.h>int main(void)
{
pid_t pid;
int fd[2];if(pipe(fd) == -1)
perror("pipe");pid = fork();
if(pid == 0) //child process: write to the pipe
{
char ch = '*';
int n = 0;close(fd[0]);
while(1)
{
write(fd[1], &ch, 1);
printf("count = %d\n", ++n);
}
}
else if(pid > 0) //parent process: wait until child process is over
{
waitpid(pid, NULL, 0);
}
}
3.实现父进程读写
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <sys/wait.h>int main(void)
{
pid_t pid;
int fd[2];if(pipe(fd) == -1)
perror("pipe");pid = fork();
if(pid == 0)
{
char tmp[100];close(fd[0]);
while(1)
{
scanf("%s", tmp);
write(fd[1], tmp, sizeof(tmp));
}
}
else if(pid > 0)
{
char tmp[100];
close(fd[1]);while(1)
{
printf("Parent process is waiting for the data from pipe:\n");
read(fd[0], tmp, sizeof(tmp));
printf("read from pipe: %s\n", tmp);
}
}return 0;
}
4.实现双向无名管道
父进程--写管道1---后读取管道2
子进程--读取管道1-转为大写,后写管道2
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <sys/wait.h>
#include <string.h>
#include <ctype.h>int main(void)
{
pid_t pid;
int fd[2];
int fd2[2];if(pipe(fd) == -1)
perror("pipe");
if(pipe(fd2) == -1)
perror("pipe");pid = fork();
if(pid == 0)
{
char tmp[100];
int i;close(fd[1]);
close(fd2[0]);while(1)
{
memset(tmp, '\0', sizeof(tmp));
read(fd[0], tmp, sizeof(tmp));for(i = 0; i < sizeof(tmp); i++)
tmp[i] = toupper(tmp[i]);write(fd2[1], tmp, sizeof(tmp));
}
}
else if(pid > 0)
{
char tmp[100];
close(fd[0]);
close(fd2[1]);while(1)
{
memset(tmp, '\0', sizeof(tmp));
gets(tmp);
write(fd[1], tmp, sizeof(tmp));memset(tmp, '\0', sizeof(tmp));
read(fd2[0], tmp, sizeof(tmp));
printf("After change: %s\n", tmp);
}
}return 0;
}