0

我最近开始使用linux,所以我对它知之甚少。至少我知道linux中的每一件事都是一个文件。

我想知道如何捕捉特定的 linux 系统返回,例如如果我选择 install ruby​​ (sudo apt-get -y install ruby​​),我怎么知道它安装成功了?

char buffer[1024];
char *buf = malloc(4096);

char *pl;
FILE *fp;

if (strcmp(cmd, "ruby") == 0)
{
        fp = popen("sudo apt-get -y install ruby", "r");
}

if (fp == NULL)
{
        printf("Failed to load file\n");
        exit(0);
}

while ((pl = fgets(buffer, sizeof(buffer), fp)) != NULL)
{
        strcat(buf, buffer);
}

strcat(buf, "\n");

pclose(fp);

然后我使用 popen 读取打开的文件,但它包含终端中显示的相同内容,我只想要一个“标志”,如 OK 或 FAIL。

对不起我糟糕的英语。

4

2 回答 2

0

apt-get 的退出代码会告诉你它是否成功(0 表示成功)。pclose(fp) 将返回退出代码,因此您可以执行以下操作:

if (pclose(fp) == 0) {
  // success
} else {
  // failure
}  

不过,您可能会注意到,现在我们实际上并没有从管道中读取。没有任何理由拥有它。因此,就像 Joachim 建议的那样, system() 函数可能更适合您的情况。

于 2012-05-25T13:29:49.513 回答
0

您需要检查正在运行的程序的退出状态。见: http: //linux.die.net/man/3/popen

The pclose() function waits for the associated process to terminate and returns the
exit status of the command as returned by wait4(2).

每个进程都提供一个退出状态(一个整数,从 0 到 255),指示程序如何/为什么结束。0 通常用于正常(成功)执行,这是您应该寻找的。

尝试查看 apt-get 的手册页或在谷歌上搜索 apt-get 的正确退出代码。

希望能帮助到你!

于 2012-05-25T13:30:51.980 回答