系统返回码()

har*_*ari 9 c unix system ps

#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;
}
Run Code Online (Sandbox Code Playgroud)

我想sudoku通过检查system()(或任何其他调用)的返回代码来查看是否正在运行.我不想在任何地方打印任何输出.

system()即使在查看手册页后,我也不太了解返回代码

无论是否sudoku正在运行,我明白了res = 0.

cni*_*tar 9

首先,你应该使用WEXITSTATUS(res).该标准明确规定:

如果command不是空指针,则system()将以waitpid()指定的格式返回命令语言解释器的终止状态.

我怀疑问题是命令实际成功(grep发现自己).尽量不要将输出重定向一会儿:

[cnicutar@fresh ~]$ ./test
  989 sh -c ps ax -o pid -o command | grep sudoku | grep gnome
res = 0
Run Code Online (Sandbox Code Playgroud)

因此,由于每个命令都成功执行,返回代码将为0 :-).你可能会有更好的运气pgrep等.


A. *_* K. 6

您尝试捕获输出的方式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;
}
Run Code Online (Sandbox Code Playgroud)

有关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;
}
Run Code Online (Sandbox Code Playgroud)