cout<<"c_addr:"<<*p_addr<
sujw 2017-08-02 06:17:20 #include <stdio.h>
#include <iostream>
#include <vector>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define PERM S_IRUSR|S_IWUSR
using namespace std;
int main()
{
string sMatch;
key_t shmid;
int *p_addr, *c_addr;
if( (shmid = shmget(IPC_PRIVATE, 1024, PERM)) == -1 ) { //(1)申请一个共享内存
fprintf(stderr, "Create Share Memory Error:%s/n/a", strerror(errno));
exit(1);
}
p_addr = (int *)shmat(shmid, 0, 0);
*p_addr = 0;
pid_t pid;
vector<string> provList;
vector<string> fileList;
provList.push_back("100");
provList.push_back("200");
provList.push_back("300");
provList.push_back("400");
provList.push_back("500");
cout<<"main process,id="<<getpid()<<endl;
//循环处理"100,200,300,400,500"
for (vector<string>::iterator it = provList.begin(); it != provList.end(); ++it)
{
sMatch=*it;
pid = fork();
if(pid==0||pid==-1) //子进程退出循环,不再创建子进程,全部由主进程创建子进程,这里是关键所在
{
break;
}
}
if(pid==-1)
{
cout<<"fail to fork!"<<endl;
exit(1);
}
else if(pid==0)
{
//这里写子进程处理逻辑
cout<<"this is children process,id="<<getpid()<<",start to process "<<sMatch<<endl;
p_addr = (int *)shmat(shmid, 0, 0);
(*p_addr)++;
sleep(3);
exit(0);
}
else
{
//这里主进程处理逻辑
cout<<"this is main process,id="<<getpid()<<",end to process "<<endl;
sleep(3);
p_addr = (int *) shmat(shmid, 0, 0);
cout<<"c_addr:"<<*p_addr<<endl;
//解除共享内存映射
if((shmdt(p_addr)) < 0)
{
perror("shmdt");
exit(1);
}
exit(0);
}
return 0;
}