您尝试捕获的输出的方式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;
}