C语言获取Shell返回结果的实现方法

前端技术 2023/09/04 C++

Linux编程时候,如果我们需要调用shell命令或脚本通常使用system方法。如system(\"ls\")

该方法返回值为0或-1,即成功或失败。而有的时候我们想要获取shell命令执行的结果,该怎么办呢?

我们可以将shell命令结果重定向到文件中,然后再读取这个文件,如:

system(\"ls>result.txt\")

FILE *fp = fopen(result, \"r\")

当然我们也可以直接使用管道,如下面示例:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <strings.h>
#include <string.h>

char* shellcmd(char* cmd, char* buff, int size)
{
  char temp[256];
  FILE* fp = NULL;
  int offset = 0;
  int len;
  
  fp = popen(cmd, \"r\");
  if(fp == NULL)
  {
    return NULL;
  }

  while(fgets(temp, sizeof(temp), fp) != NULL)
  {
    len = strlen(temp);
    if(offset + len < size)
    {
      strcpy(buff+offset, temp);
      offset += len;
    }
    else
    {
      buff[offset] = 0;
      break;
    }
  }
  
  if(fp != NULL)
  {
    pclose(fp);
  }

  return buff;
}

int main(void)
{
  char buff[1024];

  memset(buff, 0, sizeof(buff));
  printf(\"%s\", shellcmd(\"ls\", buff, sizeof(buff)));

  return 0;
}

注意:C语言调用shell命令是新建一个进程执行的,执行速度很慢,最好不要C、Shell混合编程。

以上这篇C语言获取Shell返回结果的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持phpstudy。

本文地址:https://www.stayed.cn/item/11439

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。