close

本實例主要是關於在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;

}

}


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 成功运行 的頭像
    成功运行

    成功运行的部落格

    成功运行 發表在 痞客邦 留言(0) 人氣()