popen and system

popen and system can be realized to execute shell commands in the C language code.

popen is not blocked, that will not wait for the end to kill the child process and the child process that does not manage the process. So we need to think to kill or ignore the child process and other operations. There is a result of the implementation of popen will return to buf.

system is clogged, it will automatically manage the process, we do not need to go to manage the process. In addition, system does not return the result of the execution, but will return to perform successful.

If you want to get the results of the system, refer to the following codes:

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;

}

Guess you like

Origin www.cnblogs.com/yangxingsha/p/12064734.html