急!父子进程中命名管道通讯异常
我想实现这样的功能:
父进程负责启动和管理子进程(10个子进程),当子进程未连上服务器端时,子进程退出,下次父进程重新创建子进程;当子进程对应的服务器端断开连接时,子进程也退出,父进程重新创建子进程。
代码如下:
// 父进程
while(1)
{
int iConnectFlag[10]; // 子进程的状态,0:未启动,1:启动并工作正常
pid_t pid[10];
char buffer[20];
memset( iConnectFlag,0,10*sizeof(int));
for( int i=0; i < 10; i++)
{
if( iConnectFlag[i] == 0 )
{
pid[i] = fork();
if(pid[iChannelIdx] < 0) // error, return
{
printf("fork error\n ");
}
else if (pid[i] == 0) // the child process
{
int re = connectserver(); // 连接服务器,
if(re==0)//连接成功
{
int pipe_fd;
int open_mode = O_WRONLY;
pipe_fd = open(FIFO_NAME,open_mode);
if(pipe_fd != -1)
{
sprintf(buffer,"%.2xstart", i);
int res=write(pipe_fd,Buffer,BUFFER_SIZE);
if(res==-1)
{
fprintf(stderr,"write error on pipe\n");
exit(0);
}
else
{
printf("write ok,buffer=%s\n",pchBuffer);
}
}
close(pipe_fd);
work();// 里面有while循环,一直工作,直到和服务器断开连接
sprintf(buffer,"%.2xstop!", i);
WriteToPipe( buffer);
sleep(3);
exit(0); // 子进程退出
}
else
{
int pipe_fd;
int open_mode = O_WRONLY;
pipe_fd = open(FIFO_NAME,open_mode);
if(pipe_fd != -1)
{
sprintf(buffer,"%.2xstop", i);
int res=write(pipe_fd,Buffer,BUFFER_SIZE);
if(res==-1)
{
fprintf(stderr,"write error on pipe\n");
exit(0);
}
else
{
printf("write ok,buffer=%s\n",pchBuffer);
}
}
close(pipe_fd);
sleep(3);
exit(0); // 子进程退出
}
}
else // in parent
{
}
}
else
{
int pipe_fd;
int open_mode = O_WRONLY;
pipe_fd = open(FIFO_NAME,open_mode);
if(pipe_fd != -1)
{
sprintf(buffer,"%.2xtest", i);
int res=write(pipe_fd,Buffer,BUFFER_SIZE);
if(res==-1)
{
fprintf(stderr,"write error on pipe\n");
exit(0);
}
else
{
printf("write ok,buffer=%s\n",pchBuffer);
}
}