利用Pipe实现进程间通信
基于Pipe管道实现进程间的通信
-
父进程首先使用系统调用pipe()建立一个管道,然后使用系统调用fork() 创建子进程1,子进程1关闭管道读文件,子进程1通过文件I/O操作向管道写文件写一句话(向文件中写入字符串):
Child process 1 is sending a message!
然后子进程1调用exit()结束运行。
-
父进程再次使用系统调用fork() 创建子进程2,子进程2关闭管道读文件,子进程2通过文件I/O操作向管道写文件写一句话(向文件中写入字符串):
Child process 2 is sending a message!
然后子进程2调用exit()结束运行。
-
父进程关闭管道写文件。父进程通过文件I/O操作从管道读文件中读出来自于两个子进程的信息,通过printf语句打印输出在屏幕上。
-
代码实现:
int main(void)
{
char child1_buf[] = "Child process 1 is sending a message!"; //字符串存储时包含空字符
char child2_buf[] = "Child process 2 is sending a message!";
char father_buf[75];
pid_t child1_pid;
pid_t child2_pid;
pid_t pid;
int field[2]; //文件描述符参数
if (pipe(field) == -1) //创建管道
{
printf("Failed to create the pipe\n");
return 1;
}
child1_pid = fork();
if (child1_pid == -1)
{
printf("Failed to fork\n");
return 1;
}
else if( child1_pid == 0 ) //子进程中
{
close(field[0]);
write(field[1],child1_buf,strlen(child1_buf)); //关闭读端进行写数据
printf("this is child1\n");
exit(0);
}
else //父进程中
{
int statevar1;
pid = wait(&statevar1);//等待子进程1结束
if(pid == child1_pid)
{
printf("(this is process %d) child1 process is finished,(processid is : %d) \n",getpid(),pid);
}
child2_pid = fork();
if (child2_pid == -1)
{
perror("Failed to fork");
return 1;
}
else if(child2_pid == 0 )
{
close(field[0]);
write(field[1],child2_buf,strlen(child2_buf)); //子进程二关闭读端写入消息。
printf("this is child2\n");
exit(0);
}
else
{
int statevar2;
pid = wait(&statevar2);
if(pid == child2_pid)
{
printf("(this is process %d) child2 process is finished,(processid is : %d) \n",getpid(),pid);
}
if(WIFEXITED(statevar2)) //子进程2正常结束
{
close(field[1]);
ssize_t i = read(field[0],father_buf,74);
char *buffer = "父进程从管道中读取的数据为:";
write(STDOUT_FILENO,buffer,strlen(buffer));
write(STDOUT_FILENO,father_buf,74); //关闭写端,将管道中数据全部读出。
printf("\n");
printf("this is fatherprocess:%d,message is: \"",getpid()); //依次输出每个子进程输入管道中的数据
for(int i = 0 ; i < 37 ; i++){
printf("%c",father_buf[i]);
}
printf("\" from child1 process: %d\n",child1_pid);
printf("this is fatherprocess:%d,message is: \"",getpid());
for(int i = 37 ; i < 74 ; i++){
printf("%c",father_buf[i]);
}
printf("\" from child2 process: %d\n",child2_pid);
}
else
{
printf("child2 process is not finished normally");
}
}
}
return 0;
}
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 VincentVan!
评论