Chinaunix首页 | 论坛 | 博客
  • 博客访问: 230132
  • 博文数量: 75
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 848
  • 用 户 组: 普通用户
  • 注册时间: 2013-10-08 10:27
文章分类
文章存档

2014年(9)

2013年(66)

我的朋友

分类: C/C++

2013-11-13 15:39:33

本实例主要是关于在linux上的c语言编程,涉及到pipe在master process 和 sub process之间的交互。 如何利用fork创建multi-process, 如何利用从子进程中发送信号到父进程。






#include


#include


#include


#include
#include
#include
int notify(int pipe,int pipe_in_master,int i){
printf("from child %d to notify pipe %d, where master pipe0 is pipe:%d\n",i,pipe,pipe_in_master);
//close the wirte pipe to call poll and notify master.
close(pipe);


//print the content to standard output console
fflush(stdout);
}
int main(int argc,char ** argv){




int newpipe[2];
int toclosed[8];
struct pollfd *pfd;
int pfd_count=4;
pid_t pids[4];//pid list of children stored in master
pid_t newpid;




int i=0;
while(i<8){
toclosed[i]=-1;
i++;
}




pfd = malloc(sizeof(*pfd) * 4);




i=0;
while(i<4)
{
if(pipe(&newpipe[0])<0){
printf("pipe %d failed\n",i);
continue;
}
printf("new read pipe %d in master is :%d\n",i,newpipe[0]);
if ((newpid = fork()) < 0) {
printf("fork failed %d\n",i );
close(newpipe[0]);
close(newpipe[1]);
} else if (newpid == 0) {//sub process by fork
sleep(1);
close(newpipe[0]);
notify(newpipe[1],newpipe[0], i);
_exit(1);
}
//master process by fork
pids[i]=newpid;
close(newpipe[1]);
pfd[i].fd = newpipe[0];
pfd[i].events = POLLIN;            
i++;




}




int k=0,ip=-1;
for(;;){
ip = poll(&(pfd[0]), pfd_count, -1);
k++;
printf("the %d time poll\n",k);
if (ip< 0) {               
printf("poll failed:\n");
continue;
}




for (i = 0; i < pfd_count;) {
if (!((pfd[i].revents) & (POLLIN|POLLHUP))) {
i++;
continue;

printf("wzqtest pid %d is to be closed,pipe %d is pooled \n", pids[i],pfd[i].fd);
if(toclosed[2*i]>0) close(toclosed[2*i]);
if(toclosed[2*i+1]>0) close(toclosed[2*i+1]);
kill(pids[i],SIGTERM);




/* compact the list */
if (i != (pfd_count-1)) {                         
pfd[i].fd = pfd[pfd_count-1].fd;       
pfd[i].revents = pfd[pfd_count-1].revents;




//the pids also should be compacted
pids[i]=pids[pfd_count-1];
}
pfd_count--;




}
if(pfd_count<1)
break;
}
}


阅读(1563) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~