一、system() 函数用于执行一个 shell 命令或脚本。这个函数返回的是命令的退出状态信息的高16位,而低16位是 shell 进程的退出状态码。要获取实际的退出状态,你需要使用宏来解析这个返回值。不要在shell脚本里面exit -8 这样返回负数,会提示Illegal number: -8。
二、使用demo,解释:
system("sh your_script.sh")执行 shell 脚本your_script.sh。WIFEXITED(status)用于检查 shell 脚本是否正常退出。WEXITSTATUS(status)用于获取脚本的退出状态码
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
int main() {
int status;
// 执行 shell 脚本
status = system("sh your_script.sh");
// 检查命令是否执行成功
if (status == -1) {
perror("system");
return 1;
}
// 提取和检查退出状态
if (WIFEXITED(status)) {
int exit_status = WEXITSTATUS(status);
printf("Script exited with status: %d\n", exit_status);
} else {
printf("Script did not exit normally\n");
}
return 0;
}
三、使用实例




947

被折叠的 条评论
为什么被折叠?



