c 的多进程编程实例

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



#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <string.h>
#include <signal.h>
#include <poll.h>
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;
}

}



你可能感兴趣的:(C语言,实例,fork,poll,pipe)