共2条
1/1 1 跳转至页
sock,fork 关于sock通信中的fork(),请大家看看问题在哪?
问
在sock通信中,服务器器端侦听到新的连接后,采用fork()建立新的进程处理该连接,程序如下:
if (!fork())
{ /* 子进程代码段 */
if (send(client_fd, "Hello, you are connected!\n", 26, 0) == -1)
perror("send出错!");
close(client_fd);
exit(0);
}
按上面程序,一切正常。但把程序改成如下:
if (!fork())
{ /* 子进程代码段 */
if (send(client_fd, "Hello, you are connected!\n", 26, 0) == -1)
perror("send出错!");
while(1) ;
}
sleep(3) ;
close(client_fd);
父进程延迟3秒,后把连接断开,但是始终断不开,请大家帮忙看看为什么?
如果程序改成:
if (!fork())
{ /* 子进程代码段 */
if (send(client_fd, "Hello, you are connected!\n", 26, 0) == -1)
perror("send出错!");
exit(0);
}
sleep(3) ;
close(client_fd);
父进程延迟3秒后,可以把连接断开
感觉好像只要等子进程自己断开连接或子进程结束后才能有父进程断开连接
答 1: while(1) ;很明显 ,这是一个死循环
if (!fork())
{ /* 子进程代码段 */
if (send(client_fd, "Hello, you are connected!\n", 26, 0) == -1)
perror("send出错!");
close(client_fd);
exit(0);
}
按上面程序,一切正常。但把程序改成如下:
if (!fork())
{ /* 子进程代码段 */
if (send(client_fd, "Hello, you are connected!\n", 26, 0) == -1)
perror("send出错!");
while(1) ;
}
sleep(3) ;
close(client_fd);
父进程延迟3秒,后把连接断开,但是始终断不开,请大家帮忙看看为什么?
如果程序改成:
if (!fork())
{ /* 子进程代码段 */
if (send(client_fd, "Hello, you are connected!\n", 26, 0) == -1)
perror("send出错!");
exit(0);
}
sleep(3) ;
close(client_fd);
父进程延迟3秒后,可以把连接断开
感觉好像只要等子进程自己断开连接或子进程结束后才能有父进程断开连接
答 1: while(1) ;很明显 ,这是一个死循环
共2条
1/1 1 跳转至页
我要赚赏金
