简体   繁体   English

如何捕获特定的linux系统返回

[英]How to catch a specific linux system return

I recently started to use linux, so I have little knowledge about it. 我最近开始使用linux,因此对此几乎一无所知。 At least I know that every thing in linux is a file. 至少我知道linux中的所有东西都是文件。

I would like to know how to catch a specific linux system return, for example if I choose install ruby (sudo apt-get -y install ruby), how can I know it was installed successfully? 我想知道如何捕获特定的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);

Then I am using popen to read the file opened, but it contains the same that is shown in terminal and I just want a 'flag' like OK or FAIL. 然后,我使用popen读取打开的文件,但是它包含与终端中显示的文件相同的文件,并且我只想要“ OK”或FAIL之类的“标志”。

Sorry for my poor english. 对不起,我英语不好。

The exit code of apt-get will tell you if it succeeded or not (0 means success). apt-get的退出代码将告诉您是否成功(0表示成功)。 pclose(fp) will return the exit code, so you can do: pclose(fp)将返回退出代码,因此您可以执行以下操作:

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

You may notice, though, that now we're not actually reading from the pipe. 但是,您可能会注意到,现在我们实际上并没有从管道中读取数据。 There's not really any reason to have it. 确实没有任何理由拥有它。 So like Joachim suggested, the system() function is probably a better fit for your case. 因此,如Joachim建议的那样,system()函数可能更适合您的情况。

You need to check the exit status from the program being run. 您需要检查正在运行的程序的退出状态。 See: http://linux.die.net/man/3/popen 参见: 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).

Every process provides an exit status (an integer, from 0 to 255) that indicates how/why the program ended. 每个进程都提供退出状态(0到255之间的整数),该退出状态指示程序如何/为什么终止。 0 is typically used for a normal (successful) execution, this one is the one you should be looking for. 0通常用于正常(成功)执行,这是您应该寻找的那个。

Try to see the manual page for apt-get or googling for the correct exit codes for apt-get. 尝试查看apt-get的手册页,或者查看apt-get的正确退出代码。

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM