微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

系统的返回码()

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

原文地址:https://www.jb51.cc/c/115121.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐