English 中文(简体)
如何捕捉特定的 Linux 系统返回
原标题:How to catch a specific linux system return

我最近开始使用Linux,所以我对此知之甚少。至少我知道Linux的每件东西都是文件。

我想知道如何捕捉到特定的 Linux 系统返回, 例如如果我选择安装 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
");
        exit(0);
}

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

strcat(buf, "
");

pclose(fp);

然后,我用popen读取打开的文件, 但它包含相同的文件, 显示在终端中, 我只想有像OK或FAIL这样的旗帜。

对不起,我可怜的英语。

最佳回答

pap- get 的退出代码会告诉您它是否成功( 0 表示成功) 。 pclose( fp) 将会返回退出代码, 这样您就可以做到 :

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

不过,你可能会注意到, 我们现在实际上没有从管道上读取。 没有真正的理由有它。 所以正如约阿希姆所建议, 系统() 功能可能更适合你的情况 。

问题回答

您需要检查正在运行的程序的退出状态 。 见 : < a href="http:// linux. die. net/ man/3/popen" rel= "nofollow" >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 is typically used for a normal (successful) execution, this one is the one you should be looking for.

尝试查看 app- get 或googling 的手动页面, 以获取 app- get 正确的退出代码 。

希望它能帮上忙!





相关问题
Fastest method for running a binary search on a file in C?

For example, let s say I want to find a particular word or number in a file. The contents are in sorted order (obviously). Since I want to run a binary search on the file, it seems like a real waste ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Tips for debugging a made-for-linux application on windows?

I m trying to find the source of a bug I have found in an open-source application. I have managed to get a build up and running on my Windows machine, but I m having trouble finding the spot in the ...

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

Good, free, easy-to-use C graphics libraries? [closed]

I was wondering if there were any good free graphics libraries for C that are easy to use? It s for plotting 2d and 3d graphs and then saving to a file. It s on a Linux system and there s no gnuplot ...

Encoding, decoding an integer to a char array

Please note that this is not homework and i did search before starting this new thread. I got Store an int in a char array? I was looking for an answer but didn t get any satisfactory answer in the ...

热门标签