偶爾想偷懶的我會在code中使用system(),呼叫shell來執行一些東西,並且將執行完的結果丟回來程式中處理,這時候popen就很好用了,popen - pipe stream to or from a process。
popen允許開啟read或write pipe,不能夠同時開啟為read/write,read可以讓程式從popen中讀回來處理,而write可以將程式中的資料丟到popen處理。
popen(,"r")
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { char buf[128]; float a, b, c, d; FILE *fp; if ((fp = popen("(df -h 2>/dev/null) | tail -n +2", "r")) == NULL) { fprintf(stderr, "popen() failed\n"); return -1; } while (!feof(fp)) { fscanf(fp, "%*[^ ]%f%*[^1-9]%f%*[^1-9]%f%*[^1-9]%f%%%*[^\n]", &a, &b, &c, &d); printf("%f/%f/%f/%f\n", a, b, c, d); } return 0; }
popen(,"w")
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { char buf[] = "1 2 3 4 5"; float a, b, c, d; FILE *fp; if ((fp = popen("xargs -n 1 > /tmp/xx", "w")) == NULL) { fprintf(stderr, "popen() failed\n"); return -1; } fprintf(fp, "%s", buf); pclose(fp); return 0; }
-
參考資料:
- The GNU C Library, Chapter 15.2