system() 的返回码 [英] return code of system()

查看:30
本文介绍了system() 的返回码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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() 的返回码(或任何其他与此相关的调用)来查看 sudoku 是否正在运行.我不想在任何地方打印任何输出.

I want to see if sudoku is running or not by just examining the return code of system() (or any other call for that matter). I do not want any output to be printed anywhere.

即使查看了 手册页

I do not quite understand the return code of system() even after looking at the man page

无论 sudoku 是否正在运行,我都会得到 res = 0.

Whether sudoku is running or not, I get res = 0.

推荐答案

您尝试捕获 grep 输出的方式可能不起作用.

The way you are trying to capture the output of grep may not work.

基于帖子:C:运行系统命令并获取输出?

您可以尝试以下操作.本程序使用 popen()

You can try the following. This program uses 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() 的参考,请参阅:

For reference to popen() see:

http://linux.die.net/man/3/popen

如果您尝试使用 grep 那么您可能可以重定向 grep 的输出并通过以下方式读取文件:

And if you try to use grep then you can probably redirect the output of grep and read the file in the following way:

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

这篇关于system() 的返回码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆