#include <stdlib.h> #include <string.h> #include <stdio.h> int main() { int res = system("ps ax -o pid -o command | grep sudoku | grep gnome > /dev/null"); printf("res = %d \n",res); return 0; }
我想通过检查system()的返回码(或任何其他调用)来查看数独是否正在运行.我不想在任何地方打印任何输出.
即使在查看了man page后,我也不太明白系统()的返回码
数独是否运行,我得到res = 0.
解决方法
您尝试捕获grep输出的方式可能无效.
基于帖子:
C: Run a System Command and Get Output?
你可以尝试以下几点.这个程序使用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,path); } fclose(fp); //delete the file remove ("file.txt"); return 0; }