の出力をキャプチャしようとしている方法が機能しgrep
ない場合があります。
投稿に基づく:
C: システム コマンドを実行して出力を取得しますか?
以下を試すことができます。このプログラムは popen() を使用します
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
FILE *fp;
int status;
char path[1035];
/* Open the command for reading. */
fp = popen("/bin/ps -x | /usr/bin/grep gnome-sudoku", "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit;
}
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path)-1, fp) != NULL) {
printf("%s", path);
}
pclose(fp);
return 0;
}
popen() の参照については、以下を参照してください。
http://linux.die.net/man/3/popen
そして、使用しようとするとgrep
、おそらく出力をリダイレクトgrep
して、次の方法でファイルを読み取ることができます。
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main() {
int res = system("ps -x | grep SCREEN > file.txt");
char path[1024];
FILE* fp = fopen("file.txt","r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit;
}
// Read the output a line at a time - output it.
while (fgets(path, sizeof(path)-1, fp) != NULL) {
printf("%s", path);
}
fclose(fp);
//delete the file
remove ("file.txt");
return 0;
}