前言
这两周做了很多关于共享内存,fork子进程与线程的工作,收获很大。先记录个小问题,关于主线程中fork子进程与子线程在共享内存中更新数据的问题。这些知识在书中是都能够了解到的,但如果没有亲身遭遇或者实践过,绝对不会有深切的感受。
子进程与子线程在共享内存中的区别
简单来说,有两个进程A与B,A与B通过共享内存方式实现进程间数据交换。 同时,进程A通过消息队列实时监听的进程B数据更新通知,然后进行对共享内存中的数据操作。最后,主进程通过Socket方式对进程A的数据进行访问。
实现方式一:
进程A通过fork产生的子进程实现对进程B的实时监听。整体过程如下图:
实现方式二:
进程A通过pthreadcreate创建子线程,由线程实现对进程B的实时监听。整体过程如下图:
测试demo
下面是关于fork进程时,用作小测试的程序:
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _table
{
int a;
int b;
}table;
void main()
{
int state;
pid_t pid = -1;
table *test = NULL;
test = (table *)malloc(sizeof(table));
if (!fork())
{
/* child process */
test->a = 1;
test->b = 100;
printf("child\n");
printf("test->a = %d\n", test->a);
printf("test->b = %d\n", test->b);
exit(0);
}
wait(&state);
if (pid)
{ /* father process */
printf("father\n");
printf("test->a = %d\n", test->a);
printf("test->b = %d\n", test->b);
}
}
结果如下:
总结
简单来说就是,fork子进程共享父进程资源,但涉及内存操作时,会拥有自己的独立进程空间;子线程则属于主进程空间。
版权声明:本文为fzy0201原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。