popen and system

popen与system都可在C语言代码中实现shell命令的执行。

popen是不堵塞的,也就是说不会等待子进程的结束并杀死子进程,即不会管理进程。这样就需要我们认为的去杀死或忽略子进程等操作。还有就是popen会将执行的结果返回到buf中。

system是堵塞的,会自动对进程进行管理,无需我们再去对进程进行管理。另外,system不会返回执行的结果,只是会返回执行是否成功。

若想要获取system的执行结果,可参考如下代码:

int system_result(char *cmd,char *result)
{
  char buf[1024*10]={0};
  FILE *fp=NULL;
  if(buf != NULL)
  {
    memset(buf,0,sizeof(buf));
    sprintf(buf,"%s > /tmp/cmd.txt 2>&1",cmd);
    system(buf);
    fp=fopen("/tmp/cmd.txt","r");
    if(fp == NULL) return -1;
    if(fread(result,1024,1,fp) < 0) return -1;
    if(fclose(fp) == -1) return -1;
    if(system("rm -fR /tmp/cmd.txt")) return -1;

  }else return -1;

  return 0;

}

猜你喜欢

转载自www.cnblogs.com/yangxingsha/p/12064734.html
今日推荐