C程序中如何获取shell命令执行结果和返回值
生活随笔
收集整理的這篇文章主要介紹了
C程序中如何获取shell命令执行结果和返回值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
如果在C程序中調用了shell命令,那么往往希望得到輸出結果以及命令執行的返回布爾值。在這里分為兩步來處理:
1.使用 popen 與 pclose 來執行shell命令;
2.使用‘echo $?’來獲取上一條指令執行狀態,如果為0那么標識成功執行,否則標識執行出錯;
代碼如下:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h>int main(void) {FILE *stream = NULL;char buf[1024];int ret;memset(buf, 0, sizeof(buf));if ((stream = popen("ifconfig", "r")) == NULL) {fprintf(stderr, "%s", strerror(errno));return -1;}/* output the message */while (fgets(buf, sizeof(buf), stream) != NULL) {printf("%s", buf);}if ((stream = popen("echo $?", "r")) == NULL) {fprintf(stderr, "%s", strerror(errno));return -1;}/* output the message */while (fgets(buf, sizeof(buf), stream) != NULL) {printf("%s", buf);}ret = atoi(buf);if (ret)printf("command excutes succeed!\n");else printf("command excutes fail!\n"); }總結
以上是生活随笔為你收集整理的C程序中如何获取shell命令执行结果和返回值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Deep Learning(深度学习)学
- 下一篇: XamarinEssentials教程应