回答上一个问题: https://stackoverflow.com/a/2035683/960086 没有检查和安静下来,所以我错过了它。已经被要求发布在这里
我正在玩一个在子进程上创建套接字连接的应用程序。
现在我的问题是尝试测试它,但是每次运行应用程序时,当我通过单击红色方块或右下方主(运行)X按钮关闭时,Netbeans会创建main(Build,Run)和main(Run) 。进程“终止”但它仍然存在,然后在退出IDE时它会显示“退出IDE将终止...”main(运行)“
这是我第一次使用fork(和c),所以我想在终止主进程时我没有终止子进程,但我不能手动终止吗?或者有没有办法让我有一个持续监听的套接字连接,而不会阻塞剩下的代码?
(注意连接不正确,因为它仍然有阻塞)
connection()
...
connection() {
int pid = fork();
if (pid < 0)
{
perror("ERROR on fork");
exit(1);
}
if (pid == 0)
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
fd_set fds;
struct timeval timeout;
int rc;
/* Set time limit. */
timeout.tv_sec = 0;
timeout.tv_usec = 10;
char buffer[256];
portno = 4444;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname("Localhost");
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
while(1) {
/* Create a descriptor set containing our two sockets. */
FD_ZERO(&fds);
FD_SET(sockfd, &fds);
rc = select(sizeof(fds)*8, &fds, NULL, NULL, &timeout);
if (rc==-1) {
perror("select failed");
}
if (rc > 0) {
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
}
rc = select(sizeof(fds)*8, &fds, NULL, NULL, &timeout);
if (rc==-1) {
perror("select failed");
}
if (rc > 0) {
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
printf("Client: Server send %s",buffer);
useEvent(buffer);
}
}
}