设置了setsockopt,也搞了signal(SIGCHLD, handler);,主要想处理socket通讯超时的问题。
但是发现会循环输出 printf ("成功处理一个子进程的退出\n");
void handler(int sig)
{
while (waitpid(-1, NULL, WNOHANG) > 0)
{
printf ("成功处理一个子进程的退出\n");
}
}
int main()
{
int listen_socket = Creat_socket();
signal(SIGCHLD, handler); //处理子进程,防止僵尸进程的产生
while(1)
{
int client_socket = wait_client(listen_socket); //多进程服务器,可以创建子进程来处理,父进程负责监听。
int pid = fork();
if(pid == -1)
{
perror("fork");
break;
}
if(pid > 0)
{
close(client_socket);
continue;
}
if(pid == 0)
{
close(listen_socket);
struct timeval timeout;
timeout.tv_sec=60;
timeout.tv_usec=0;
if (-1 ==setsockopt(client_socket,SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,sizeof(timeout)))
{
}
if (-1 ==setsockopt(client_socket,SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,sizeof(timeout)))
{
}
hanld_client(listen_socket, client_socket);
break;
}
}
close(listen_socket);
return 0;
}
main()
里不是有个while(1){}
么,父进程不断地在创建子进程,子进程不断推出,自然一直在输出“成功处理一个子进程的退出”了。
你是把fork()
的返回给父子进程的值得判断搞反了吧
那应该怎么写啊
@Dellienware: man fork看说明。fork()返回值大于0是回到父进程,等于0是回到子进程,因此交换一下if( pid > 0 )
和if( pid == 0)
的处理代码就可以了。
Return Value
On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.