如何修复端口占用问题

问题由来

最近在做项目时,遇到一个很恶心的问题,当启动server时,因为工程在运行时会创建socket因此会占用端口,可是在析构或者遇到崩溃的情况时,端口并没有释放。于是当第二次启动,就会出现端口被占用问题。
  解决方案
当检测到端口被占用时, 查询端口占用情况,会返回端口占用的进程信息。如果被占用,就把占用的进程kill掉。 在c++中,如果要执行shell语句,最好是通过popen()来执行。(popen请看
执行lsof -i:%d(端口号) 来查询占用端口的相关进程信息。然后通过fget把文件流写入到字符串中。再通过strtok(buff, “ “)截取PID信息,最口通过Linux的kill(pID, SIGKILL)直接kill那个占用端口的进程就可以了。下面上相关的代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
int PrepareToStart(int port) {
大专栏  如何修复端口占用问题/> FILE *pstr;
char cmd[128], buff[512], *p;
pid_t pID;
int pidnum;
int ret = 3;
memset(buff, 0, sizeof(buff));
sprintf(cmd, "lsof -i:%d ", port);
pstr = popen(cmd, "r"); //
if (pstr == NULL) {
return 1;
}
memset(buff, 0, sizeof(buff));
while (fgets(buff, 128 - 1, pstr) != NULL) {
}
printf("%s", buff);
p = strtok(buff, " ");
LOG(INFO) << p;
LOG(INFO) << buff;
p = strtok(NULL, " ");
LOG(INFO) << p;
if (p == NULL) {
return 1;
}
if (strlen(p) == 0) {
return 1;
}
if ((pidnum = atoi(p)) == 0) {
return 1;
}
printf("pidnum: %dn", pidnum);
pID = (pid_t) pidnum;
ret = kill(pID, SIGKILL);
printf("ret= %d n", ret);
return ret;
}

猜你喜欢

转载自www.cnblogs.com/liuzhongrong/p/12371114.html