开始循环fork子进程,每个子进程等待前一个子进程结束后才结束
/* description: communicate between child process and parent processes
*
* fork every child process and arrange them being ended in order.
*
* date : 2015/11/23
*
*
*/
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#include <malloc.h>
#include <string.h>
#include <stdlib.h>
int number = 3;
//-----------------for pipe communication
char cmdBegin[10] = "begin";
char cmdEnd[10] = "end";
int main(int argc, char *argv[])
{
// calculate running time
struct timeval tvbegin, tvend;
gettimeofday(&tvbegin, NULL);
//-----------------pipe
int (* fd) [2] = (int (*)[2]) malloc (sizeof(int) * 2 * number);
if(pipe(fd[0]) < 0)
{
printf("pipe [0] error\n");
exit(1);
}
write(fd[0][1], cmdEnd, strlen(cmdEnd));
int iChild;
for(iChild = 0; iChild < number; iChild++)
{
if(pipe(fd[iChild]) < 0)
{
printf("pipe [%d] error\n", iChild);
exit(1);
}
int child = fork();
if(child == -1)
{
printf("fork [%d] child process error\n", iChild);
}
else if(child == 0)
{
printf ("----child:%d began.\n", iChild + 1);
//-----------------wait the front child process to end
if(iChild > 0)
{
close(fd[iChild - 1][1]);
char cmd [10] = {0};
read(fd[iChild - 1][0], cmd, sizeof(cmd));
while(strcmp(cmd, cmdEnd) != 0)
{
usleep(10);
read(fd[iChild - 1][0], cmd, sizeof(cmd));
}
}
//-----------------write the pipe
close(fd[iChild][0]);
write(fd[iChild][1], cmdEnd, strlen(cmdEnd));
printf ("----child:%d ended.\n", iChild + 1);
exit(0);
}
}
//-----------------wait the last child process to end
close(fd[iChild - 1][1]);
char cmd [10] = {0};
read(fd[iChild - 1][0], cmd, sizeof(cmd));
while(strcmp(cmd, cmdEnd) != 0)
{
usleep(10);
read(fd[iChild - 1][0], cmd, sizeof(cmd));
}
printf ("all complete!\n");
free(fd);
gettimeofday(&tvend, NULL);
printf("cost %d ms\n", (tvend.tv_sec-tvbegin.tv_sec)*1000+(tvend.tv_usec-tvbegin.tv_usec)/1000);
return 0;
}
运行结果
[root@localhost training]# ./test
—-child:2 began.
—-child:3 began.
—-child:1 began.
—-child:1 ended.
—-child:2 ended.
—-child:3 ended.
all complete!
cost 2 ms