替换system函数,减少资源开销,用 posix_spawn函数

📅 2026/7/8 2:37:31 👁️ 阅读次数 📝 编程学习
替换system函数,减少资源开销,用 posix_spawn函数

替换system函数,减少资源开销,用 posix_spawn函数

system("ifconfig wlan0 up 192.168.6.1"); // 等价于 int set_wlan0_ap_ip(const char *iface, const char *ip) { pid_t pid; char *argv[] = { "ifconfig", iface, "up", ip, NULL }; int ret = posix_spawn(&pid, "/sbin/ifconfig", NULL, NULL, argv, NULL); if (ret != 0) { printf("posix_spawn failed: %d\n", ret); return -1; } // 等待 ifconfig 执行完成 int status; waitpid(pid, &status, 0); if (WIFEXITED(status) && WEXITSTATUS(status) == 0) { printf("IP set successfully\n"); return 0; } else { printf("ifconfig failed\n"); return -1; } } // 调用示例 set_wlan0_ap_ip("wlan0", "192.168.6.1");