系统的返回码()

#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;
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...