C语言使用popen循环调用lua产生很多僵尸进程,最后导致系统挂掉sh: can't fork
僵尸进程:
11063 root 0 Z [sh] 11068 root 0 Z [sh] 11072 root 0 Z [sh] 11075 root 0 Z [sh] 11078 root 0 Z [sh] 11080 root 0 Z [sh] 11082 root 0 Z [sh] 11084 root 0 Z [sh]
问题:用fclose关闭popen是错误的,会导致fd泄漏,达到一定的数量就不能再创建子进程了
解决:把fclose换成pclose关闭popen。
#include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { char payload[1024] = {0}; FILE *fp; fp = popen("exec /usr/bin/lua /tmp/abc.lua", "r");if (NULL == fp) return -1; fgets(payload, 1024, fp); if (payload[strlen(payload) - 1] == '\n') { payload[strlen(payload) - 1] = '\0'; } pclose(fp); }
If you use fclose on the pipe, you will have file descriptor leaks, since fclose will not free the file pointer in the kernel (which is created when you create the pipe since its a file).
While your testing so far hasn't shown any problems, run your program 3000 times (or how ever many file descriptors are allowed, upwards of an int I think) and watch when you will n o longer be able to create pipes.
参考:https://stackoverflow.com/questions/18318357/use-fclose-to-pipe-of-popen-is-a-serious-bug
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)