C中如何获取执行shell命令的响应结果?

how to get the responding result of executing shell command in C?

更新:我尝试打印 system() 的 return 值。如果 ssh 失败,它将 return 65280,如果成功,它将 returns 0.

我想从我的笔记本电脑 ssh 到另一台机器,我写了一个 C 程序,它访问那台机器并触摸那台机器上的文件。但有时网络不稳定或者那台机器坏了。因此,ssh 将失败。我怎么知道 ssh 在那个程序中失败了?有时候ssh到那台机器成功了,但是touch那个文件失败了,在C程序中怎么区分呢?我怎么知道 shell 命令失败是因为 ssh 失败而不是 touch?我不想盯着屏幕看,我希望程序自动检查。

here is my code:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int  main(int argc,const char *argv[])
{
while(1)
{
    system("ssh liulyix@localhost -p 22210 'touch script/rebooter.sh'");
    sleep(5);
}
}

阅读系统手册页。

原型类型是

int system (constant char *command)

return 值为 -1 系统由于分叉失败而无法执行命令。查看 execve 的手册页并查看可能引发的错误号。所有这些错误都是系统将 return -1.

的原因

所有其他 returns ed 值是命令的退出代码。 0 表示成功,所有其他值表示命令因 EXIT_FAILURE.

而崩溃

使用函数popen()会更容易:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int  main(int argc,const char *argv[])
{
   FILE *fp;
   fp = popen("ssh liulyix@localhost -p 22210 'touch script/rebooter.sh'", "r");
   while(1)
  {
    char *line; char buf[1024];
   line = fgets(buf, 1024, fp);
   if (line == NULL) break;
   printf("%s", line);

  }
  pclose(fp);
  return 0;
}