共享内存实现父子进程间通讯
2014-06-04 13:36
387 查看
//共享内存实现父子进程间通讯
//2013-10-30
//yang
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/ipc.h>
#include<sys/shm.h>
int main(void)
{
int shmid,pid=0,stop=3;
char *shm_p=NULL;
shmid = shmget(123456,2028,0600|IPC_CREAT);
//创建共享内存
if(shmid == -1)
{
perror("shmget");
return 1;
}
shm_p = shmat(0600|IPC_CREAT,NULL,0);
//对共享内存的映射实现父子进程可以调用内存
if(shm_p == NULL)
{
perror("shmat");
return 1;
}
pid = fork();
//创建进程
if(pid < 0)
{
printf("fork error");
}
if(pid == 0)
//子进程
{
shm_p =(char *)malloc(strlen("hello...属于子进程")+1);
while(shm_p[0] != 'h')
{
memset(shm_p,'\0',strlen("hello...属于子进程")+1);
memcpy(shm_p,"hello...属于子进程",strlen("hello...属于子进程")+1);
}
puts(shm_p);
exit(stop);
}
else //父进程
{
wait(&stop);
//sleep(2);
shm_p =(char *)malloc(strlen("world...属于父进程")+1);
while(shm_p[0] != 'w')
{
memset(shm_p,'\0',strlen("world...属于父进程")+1);
strcat(shm_p,"world...属于父进程");
}
}
puts(shm_p);
free(shm_p);
shm_p = NULL;
}
//2013-10-30
//yang
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/ipc.h>
#include<sys/shm.h>
int main(void)
{
int shmid,pid=0,stop=3;
char *shm_p=NULL;
shmid = shmget(123456,2028,0600|IPC_CREAT);
//创建共享内存
if(shmid == -1)
{
perror("shmget");
return 1;
}
shm_p = shmat(0600|IPC_CREAT,NULL,0);
//对共享内存的映射实现父子进程可以调用内存
if(shm_p == NULL)
{
perror("shmat");
return 1;
}
pid = fork();
//创建进程
if(pid < 0)
{
printf("fork error");
}
if(pid == 0)
//子进程
{
shm_p =(char *)malloc(strlen("hello...属于子进程")+1);
while(shm_p[0] != 'h')
{
memset(shm_p,'\0',strlen("hello...属于子进程")+1);
memcpy(shm_p,"hello...属于子进程",strlen("hello...属于子进程")+1);
}
puts(shm_p);
exit(stop);
}
else //父进程
{
wait(&stop);
//sleep(2);
shm_p =(char *)malloc(strlen("world...属于父进程")+1);
while(shm_p[0] != 'w')
{
memset(shm_p,'\0',strlen("world...属于父进程")+1);
strcat(shm_p,"world...属于父进程");
}
}
puts(shm_p);
free(shm_p);
shm_p = NULL;
}
相关文章推荐
- 进程间通讯的消息队列和共享内存方式的实现
- 在VC++ 6.0下利用共享内存、消息实现内部进程通讯
- 进程间通讯----消息队列和共享内存方式的实现
- linux多线程【8】mmap实现父子进程的共享内存通信,用信号量同步
- 利用共享内存实现进程之间的通讯
- linux_c语言实现父子进程共享内存
- 用文件映射(File Mapping)实现进程间内存共享
- 共享内存实现进程间大数据的交换
- 共享内存实现进程间大数据的交换
- Linux下通过共享内存进行进程间通信,进程间同步使用信号量来实现
- 共享内存实现进程间大数据的交换
- VC 共享内存实现进程间大数据的交换
- Linux进程间通讯之共享内存
- 通过内存映射文件实现进程间数据共享
- 共享内存实现进程间数据的交换
- 共享内存实现进程间大数据的交换
- 共享内存实现进程间大数据的交换
- 进程间通讯共享内存的具体步骤
- 利用共享存储实现父子进程间的通信
- 进程间通讯-共享内存2(代码)