当前位置: 首页>>代码示例>>C++>>正文


C++ pclose函数代码示例

本文整理汇总了C++中pclose函数的典型用法代码示例。如果您正苦于以下问题:C++ pclose函数的具体用法?C++ pclose怎么用?C++ pclose使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了pclose函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: defined

std::string CNetworkInterfaceLinux::GetCurrentDefaultGateway(void)
{
   std::string result;

#if defined(TARGET_DARWIN)
  FILE* pipe = popen("echo \"show State:/Network/Global/IPv4\" | scutil | grep Router", "r");
  Sleep(100);
  if (pipe)
  {
    std::string tmpStr;
    char buffer[256] = {'\0'};
    if (fread(buffer, sizeof(char), sizeof(buffer), pipe) > 0 && !ferror(pipe))
    {
      tmpStr = buffer;
      if (tmpStr.length() >= 11)
        result = tmpStr.substr(11);
    }
    pclose(pipe);
  }
  if (result.empty())
    CLog::Log(LOGWARNING, "Unable to determine gateway");
#elif defined(TARGET_FREEBSD)
   size_t needed;
   int mib[6];
   char *buf, *next, *lim;
   char line[16];
   struct rt_msghdr *rtm;
   struct sockaddr *sa;
   struct sockaddr_in *sockin;

   mib[0] = CTL_NET;
   mib[1] = PF_ROUTE;
   mib[2] = 0;
   mib[3] = 0;
   mib[4] = NET_RT_DUMP;
   mib[5] = 0;
   if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
      return result;

   if ((buf = (char *)malloc(needed)) == NULL)
      return result;

   if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
      free(buf);
      return result;
   }

   lim  = buf + needed;
   for (next = buf; next < lim; next += rtm->rtm_msglen) {
      rtm = (struct rt_msghdr *)next;
      sa = (struct sockaddr *)(rtm + 1);
      sa = (struct sockaddr *)(SA_SIZE(sa) + (char *)sa);	
      sockin = (struct sockaddr_in *)sa;
      if (inet_ntop(AF_INET, &sockin->sin_addr.s_addr,
         line, sizeof(line)) == NULL) {
            free(buf);
            return result;
	  }
	  result = line;
      break;
   }
   free(buf);
#else
   FILE* fp = fopen("/proc/net/route", "r");
   if (!fp)
   {
     // TBD: Error
     return result;
   }

   char* line = NULL;
   char iface[16];
   char dst[128];
   char gateway[128];
   size_t linel = 0;
   int n;
   int linenum = 0;
   while (getdelim(&line, &linel, '\n', fp) > 0)
   {
      // skip first two lines
      if (linenum++ < 1)
         continue;

      // search where the word begins
      n = sscanf(line,  "%16s %128s %128s",
         iface, dst, gateway);

      if (n < 3)
         continue;

      if (strcmp(iface, m_interfaceName.c_str()) == 0 &&
          strcmp(dst, "00000000") == 0 &&
          strcmp(gateway, "00000000") != 0)
      {
         unsigned char gatewayAddr[4];
         int len = CNetwork::ParseHex(gateway, gatewayAddr);
         if (len == 4)
         {
            struct in_addr in;
            in.s_addr = (gatewayAddr[0] << 24) | (gatewayAddr[1] << 16) |
//.........这里部分代码省略.........
开发者ID:moatstormer,项目名称:mrmc,代码行数:101,代码来源:NetworkLinux.cpp

示例2: printf

void *computervision_thread_main(void* data)
{
  // Video Input
  struct vid_struct vid;
  vid.device = (char*)"/dev/video1";
  vid.w=1280;
  vid.h=720;
  vid.n_buffers = 4;
  if (video_init(&vid)<0) {
    printf("Error initialising video\n");
    computervision_thread_status = -1;
    return 0;
  }

  // Frame Grabbing
  struct img_struct* img_new = video_create_image(&vid);

  // Frame Resizing
  uint8_t quality_factor = IMAGE_QUALITY_FACTOR;
  uint8_t dri_jpeg_header = 1;

  struct img_struct small;
  small.w = vid.w / IMAGE_DOWNSIZE_FACTOR;
  small.h = vid.h / IMAGE_DOWNSIZE_FACTOR;
  small.buf = (uint8_t*)malloc(small.w*small.h*2);

  // Commpressed image buffer
  uint8_t* jpegbuf = (uint8_t*)malloc(vid.h*vid.w*2);

  // file index (search from 0)
  int file_index = 0;

  int microsleep = (int)(1000000. / IMAGE_FPS);

  while (computer_vision_thread_command > 0)
  {
    usleep(microsleep);
    video_grab_image(&vid, img_new);

    // Resize
    resize_uyuv(img_new, &small, IMAGE_DOWNSIZE_FACTOR);

    // JPEG encode the image:
    uint32_t image_format = FOUR_TWO_TWO;  // format (in jpeg.h)
    uint8_t* end = encode_image (small.buf, jpegbuf, quality_factor, image_format, small.w, small.h, dri_jpeg_header);
    uint32_t size = end-(jpegbuf);

#if IMAGE_SAVE
    FILE* save;
    char save_name[128];
    if (system("mkdir -p /data/video/images") == 0) {
      // search available index (max is 99)
      for ( ; file_index < 99; file_index++) {
        printf("search %d\n",file_index);
        sprintf(save_name,"/data/video/images/img_%02d.jpg",file_index);
        // test if file exists or not
        if (access(save_name, F_OK) == -1) {
          printf("access\n");
          save = fopen(save_name, "w");
          if (save != NULL) {
            fwrite(jpegbuf, sizeof(uint8_t), size, save);
            fclose(save);
          }
          else {
            printf("Error when opening file %s\n", save_name);
          }
          // leave for loop
          break;
        }
        else {printf("file exists\n");}
      }
    }
#endif

    // Fork process
    int status;
    pid_t pid = fork();

    if (pid == 0) {
      // Open process to send using netcat in child process
      char nc_cmd[64];
      sprintf(nc_cmd, "nc %s %d", IMAGE_SERVER_IP, IMAGE_SERVER_PORT);
      FILE* netcat;
      netcat = popen(nc_cmd, "w");
      if (netcat != NULL) {
        fwrite(jpegbuf, sizeof(uint8_t), size, netcat);
        if (pclose(netcat) == 0) {
          printf("Sending image succesfully\n");
        }
      }
      else {
        printf("Fail sending image\n");
      }
      exit(0);
    }
    else if (pid < 0) {
      printf("Fork failed\n");
    }
    else {
      // Parent is waiting for child to terminate
//.........这里部分代码省略.........
开发者ID:KISSMonX,项目名称:paparazzi,代码行数:101,代码来源:image_nc_send.c

示例3: FPutFile

int FPutFile(TRUSERID *handle,int iRequest,ST_PACK *rPack,int *pRetCode,char *szMsg)
{
	//ST_SDPACK *psd;
	int ret;
	char szCmd[256] = "";
	char filepath[256]="";
	char sFileName[256]={0};
	char chkdate[9] = "";
	FILE *fp;
	struct stat fst;
	memset(&fst,0,sizeof fst);

	printf("filetransfer:主动获取对账文件标志[%d]\n", rPack->lvol2);
	
	if(rPack->lvol2==1)			// 需主动获取对账文件
	{
		ret = Bank_Checkacc(handle,rPack,pRetCode,szMsg);
		if(ret)
		{
			sprintf(szMsg, "FPutFile:下载对账文件请求失败,错误代码[%d]", ret);
			printf(szMsg);
			return -1;
		}

		printf("FPutFile:下载对账文件请求成功\n");
	}
	
	/* 重命名文件
	将银行chkdate 那天的对账文件,改名为 sFileName
	*/
	sprintf(szCmd,"getbankchkfile.sh %s",rPack->vsmess);

	printf("FPutFile:szCmd[%s]\n", szCmd);

	if((fp = popen(szCmd, "r"))==NULL)
	{
		sprintf(szMsg, "exec cmd[%s] error",szCmd);
		return -1;
	}
	char line[1024]={0};
	char lastline[1024]={0};
	while(!feof(fp))
	{
		memset(line,0,sizeof(line));
		if(fgets(line, sizeof(line),fp)==NULL)
		{
			if(feof(fp))
				break;
			else
			{
				pclose(fp);
				return -1;
			}
		}
		strcpy(lastline,line);
		if(strstr(line,"filename:")!=0)
		{
			strcpy(sFileName,line+strlen("filename:"));
			break;
		}		
	}
	pclose(fp);

	printf("FPutFile:sFileName[%s]\n", sFileName);
	
	if(strlen(sFileName)<1)
	{
		printf("FPutFile:%s\n", lastline);
		strcpy(szMsg,lastline);
		return -1;
	}
	
	trim(sFileName);
	printf("downfile:[%s]\n",sFileName);
	stat(sFileName, &fst);
	printf("filelen:%d\n", fst.st_size);
	int maxlen = sizeof(ST_PACK) - 4;
	if (maxlen > 4000)
		maxlen = 4000;
	fp = fopen(sFileName, "rb");
	if (fp == NULL)
	{
		sprintf(szMsg, "Cannot open the file:<%s>!", sFileName);
		return  9999;
	}
	ST_SDPACK *psd=(ST_SDPACK *)rPack;
	if(fst.st_size>0)
	{
		while (!feof(fp))
		{	
			psd->usDataLength = fread(psd->data, 1, maxlen, fp);
			PutRowData(rPack);
		}
	}
	fclose(fp);		

	ST_CPACK aPack;
	ST_PACK *outPack = &(aPack.pack);
	ResetNormalCPack(&aPack,0,1);
	SetCol(handle,0);
//.........这里部分代码省略.........
开发者ID:nykma,项目名称:ykt4sungard,代码行数:101,代码来源:FPutFile.cpp

示例4: xlibdir

// Fetch the X library directory, using xmkmf(1)
static const _XtString xlibdir(Display *display, bool verbose = false)
{
    static bool tried = false;
    static const _XtString dir = 0;

    if (tried)
	return dir;
    tried = true;

    if (!is_cmd_file(cmd_file("xmkmf")))
	return dir;		// No `xmkmf' in PATH
    if (!is_cmd_file(cmd_file("make")))
	return dir;		// No `make' in PATH

    static const char *shell_command =
	""
#include "xlibdir.C"
	"";

    String me, my_class;
    XtGetApplicationNameAndClass(display, &me, &my_class);

    if (verbose)
    {
	std::cout << "Checking for X11 library directory... ";
	std::cout.flush();
    }

    const string s1 = "/bin/sh -c " + sh_quote(shell_command); 
    FILE *fp = popen(s1.chars(), "r");
    if (fp == 0)
    {
	if (verbose)
	{
	    std::cout << strerror(errno) << "\n";
	    std::cout.flush();
	}
	return dir;
    }

    char buffer[PATH_MAX];
    buffer[0] = '\0';
    fgets(buffer, sizeof(buffer), fp);
    pclose(fp);

    int len = strlen(buffer);
    if (len > 0 && buffer[len - 1] == '\n')
	buffer[len - 1] = '\0';

    if (buffer[0] == '/')	// Sanity check
	dir = (String)XtNewString(buffer);

    if (verbose)
    {
	if (dir)
	    std::cout << dir << "\n";
	else
	    std::cout << "(not found)\n";
	std::cout.flush();
    }

    return dir;
}
开发者ID:KrisChaplin,项目名称:octeon_toolchain-4.1,代码行数:64,代码来源:xconfig.C

示例5: generate_sql_makefile

bool generate_sql_makefile()
{
    if (new_sql_updates.empty()) return true;

    // find all files in the update dir
    snprintf(cmd, MAX_CMD, "git show HEAD:%s", sql_update_dir);
    if ((cmd_pipe = popen(cmd, "r")) == NULL)
        return false;

    // skip first two lines
    if (!fgets(buffer, MAX_BUF, cmd_pipe)) { pclose(cmd_pipe); return false; }
    if (!fgets(buffer, MAX_BUF, cmd_pipe)) { pclose(cmd_pipe); return false; }

    char newname[MAX_PATH];
    std::set<std::string> file_list;
    sql_update_info info;

    while (fgets(buffer, MAX_BUF, cmd_pipe))
    {
        buffer[strlen(buffer) - 1] = '\0';
        if (buffer[strlen(buffer) - 1] != '/' &&
                strncmp(buffer, "Makefile.am", MAX_BUF) != 0)
        {
            if (new_sql_updates.find(buffer) != new_sql_updates.end())
            {
                if (!get_sql_update_info(buffer, info)) return false;
                snprintf(newname, MAX_PATH, REV_PRINT "_%s_%0*d_%s%s%s.sql", rev, info.parentRev, 2, info.nr, info.db, info.has_table ? "_" : "", info.table);
                file_list.insert(newname);
            }
            else
                file_list.insert(buffer);
        }
    }

    pclose(cmd_pipe);

    // write the makefile
    char file_name[MAX_PATH];
    snprintf(file_name, MAX_PATH, "%s%s/Makefile.am", path_prefix, sql_update_dir);
    FILE* fout = fopen(file_name, "w");
    if (!fout) { pclose(cmd_pipe); return false; }

    fprintf(fout,
            "# This code is part of MaNGOS. Contributor & Copyright details are in AUTHORS/THANKS.\n"
            "#\n"
            "# This program is free software; you can redistribute it and/or modify\n"
            "# it under the terms of the GNU General Public License as published by\n"
            "# the Free Software Foundation; either version 2 of the License, or\n"
            "# (at your option) any later version.\n"
            "#\n"
            "# This program is distributed in the hope that it will be useful,\n"
            "# but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
            "# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
            "# GNU General Public License for more details.\n"
            "#\n"
            "# You should have received a copy of the GNU General Public License\n"
            "# along with this program; if not, write to the Free Software\n"
            "# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
            "\n"
            "## Process this file with automake to produce Makefile.in\n"
            "\n"
            "## Sub-directories to parse\n"
            "SUBDIRS = before_upgrade_to_0.13\n"
            "\n"
            "## Change installation location\n"
            "#  datadir = mangos/%s\n"
            "pkgdatadir = $(datadir)/mangos/%s\n"
            "\n"
            "## Files to be installed\n"
            "#  Install basic SQL files to datadir\n"
            "pkgdata_DATA = \\\n",
            sql_update_dir, sql_update_dir
    );

    for(std::set<std::string>::iterator itr = file_list.begin(), next; itr != file_list.end(); ++itr)
    {
        next = itr; ++next;
        fprintf(fout, "\t%s%s\n", itr->c_str(), next == file_list.end() ? "" : " \\");
    }

    fprintf(fout,
            "\n## Additional files to include when running 'make dist'\n"
            "#  SQL update files, to upgrade database schema from older revisions\n"
            "EXTRA_DIST = \\\n"
           );

    for (std::set<std::string>::iterator itr = file_list.begin(), next; itr != file_list.end(); ++itr)
    {
        next = itr; ++next;
        fprintf(fout, "\t%s%s\n", itr->c_str(), next == file_list.end() ? "" : " \\");
    }

    fclose(fout);

    snprintf(cmd, MAX_CMD, "git add %s%s/Makefile.am", path_prefix, sql_update_dir);
    system_switch_index(cmd);

    return true;
}
开发者ID:Anderlobi1,项目名称:server,代码行数:99,代码来源:git_id.cpp

示例6: log_err

struct chipInfo_t *getChipInfo(const char *filename, int *num, uint32_t msmversion)
{

    const char str1[] = "dtc -I dtb -O dts \"";
    const char str2[] = "\" 2>&1";
    char *buf, *pos;
    char *line = NULL;
    size_t line_size;
    FILE *pfile;
    int llen;
    struct chipInfo_t *chip = NULL, *tmp;
    uint32_t data[3] = {0, 0, 0};
    uint32_t data_st[2] = {0, 0};
    char *tok, *sptr = NULL;
    int i, entryValid, entryEnded;
    int count = 0, count1 = 0, count2 =0;
    int entryValidST, entryEndedST, entryValidDT, entryEndedDT;
    struct chipId_t *chipId = NULL, *cId = NULL, *tmp_id = NULL;
    struct chipSt_t *chipSt = NULL, *cSt = NULL, *tmp_st = NULL;

    line_size = 1024;
    line = (char *)malloc(line_size);
    if (!line) {
        log_err("Out of memory\n");
        return NULL;
    }

    llen = sizeof(char) * (strlen(dtc_path) +
                           strlen(str1) +
                           strlen(str2) +
                           strlen(filename) + 1);
    buf = (char *)malloc(llen);
    if (!buf) {
        log_err("Out of memory\n");
        free(line);
        return NULL;
    }

    strncpy(buf, dtc_path, llen);
    strncat(buf, str1, llen);
    strncat(buf, filename, llen);
    strncat(buf, str2, llen);

    pfile = popen(buf, "r");
    free(buf);

    if (pfile == NULL) {
        log_err("... skip, fail to decompile dtb\n");
    } else {
        /* Find "qcom,msm-id" */
        while ((llen = getline(&line, &line_size, pfile)) != -1) {
            if (msmversion == 1) {
                if ((pos = strstr(line, dt_tag)) != NULL) {
                    pos += strlen(dt_tag);

                    entryEnded = 0;
                    while (1) {
                        entryValid = 1;
                        for (i = 0; i < 3; i++) {
                            tok = strtok_r(pos, " \t", &sptr);
                            pos = NULL;
                            if (tok != NULL) {
                                if (*tok == '>') {
                                    entryEnded = 1;
                                    entryValid = 0;
                                    break;
                                }
                                data[i] = strtoul(tok, NULL, 0);
                            } else {
                                data[i] = 0;
                                entryValid = 0;
                                entryEnded = 1;
                            }
                        }
                        if (entryEnded) {
                            free(line);
                            pclose(pfile);
                            *num = count;
                            return chip;
                        }
                        if (entryValid) {
                            tmp = (struct chipInfo_t *)
                                      malloc(sizeof(struct chipInfo_t));
                            if (!tmp) {
                                log_err("Out of memory\n");
                                break;
                            }
                            if (!chip) {
                                chip = tmp;
                                chip->t_next = NULL;
                            } else {
                                tmp->t_next = chip->t_next;
                                chip->t_next = tmp;
                            }
                            tmp->chipset  = data[0];
                            tmp->platform = data[1];
                            tmp->subtype  = 0;
                            tmp->revNum   = data[2];
                            tmp->dtb_size = 0;
                            tmp->dtb_file = NULL;
//.........这里部分代码省略.........
开发者ID:AndroPlus-org,项目名称:android_device_sony_shinano-common,代码行数:101,代码来源:dtbtool.c

示例7: nonInteractive_appendClipboardContents

/* Reads the output of command into buffer then inserts into a MESSAGE struct. */
void nonInteractive_appendClipboardContents( MESSAGE *msg, char *command ) {

    /* Loop to the end of the message */
    msg = msg->root;
    for ( ; msg->next; msg = msg->next )
        ;

    /* Allocate and move to new node */
    msg->next = list_getNode( msg );
    msg = msg->next;

    /* Get and set path and time information */
    list_setPath( msg );
    list_setTime( msg );

    char *tmp, *buffer;
    tmp = buffer = NULL;

    int buffSize, ch, charsRead;
    buffSize = 1024;
    charsRead = 0;

    buffer = malloc( buffSize * sizeof(char) );

    if ( !buffer ) {
        fprintf( stderr,
                "Failed to allocate memory for message buffer in nonInteractive_appendClipboardContents\n" );
        exit( 1 );
    }

    FILE *fp;

    /* Open the command for reading. */
    fp = popen( command, "r" );
    if ( fp == NULL ) {
        printf( "Failed to run command\n" );
        exit( 1 );
    }

    while ( ( ch = fgetc( fp ) ) != EOF ) {

        /* If we've outgrown the buffer then allocate some more memory */
        if ( charsRead >= buffSize ) {
            buffSize *= 2;
            tmp = realloc( buffer, buffSize * sizeof(char *) );

            if ( !tmp ) {
                fprintf( stderr,
                        "Failed to allocate %d bytes in nonInteractive_appendMessage\n",
                        buffSize );
                exit( 1 );
            } else {
                buffer = tmp;
            }
        } else {
            /* Otherwise add the character to the buffer and increment charsRead */
            buffer[charsRead] = ch;
            charsRead++;
        }
    }

    /* Insert the buffer contents into a MESSAGE struct */
    list_insertString( msg, buffer );

    free( buffer );
    pclose( fp );
}
开发者ID:nadams810,项目名称:terminote2,代码行数:68,代码来源:nonInteractive.c

示例8: fileInDirectory


//.........这里部分代码省略.........

				map.resize( metaTileSizeX * m_settings.tileSize + 2 * m_settings.margin, metaTileSizeY * m_settings.tileSize + 2 * m_settings.margin );

				ProjectedCoordinate drawTopLeft( x - 1.0 * m_settings.margin / m_settings.tileSize, y - 1.0 * m_settings.margin / m_settings.tileSize, zoom );
				ProjectedCoordinate drawBottomRight( x + metaTileSizeX + 1.0 * m_settings.margin / m_settings.tileSize, y + metaTileSizeY + 1.0 * m_settings.margin / m_settings.tileSize, zoom );
				GPSCoordinate drawTopLeftGPS = drawTopLeft.ToGPSCoordinate();
				GPSCoordinate drawBottomRightGPS = drawBottomRight.ToGPSCoordinate();
				projection.forward( drawTopLeftGPS.longitude, drawBottomRightGPS.latitude );
				projection.forward( drawBottomRightGPS.longitude, drawTopLeftGPS.latitude );
				mapnik::box2d<double> boundingBox( drawTopLeftGPS.longitude, drawTopLeftGPS.latitude, drawBottomRightGPS.longitude, drawBottomRightGPS.latitude );
				map.zoom_to_box( boundingBox );
				mapnik::agg_renderer<mapnik::image_32> renderer( map, image );
				renderer.apply();

				std::string data;
				int skipped = 0;
				int saved = 0;
				for ( int subX = 0; subX < metaTileSizeX; ++subX ) {
					for ( int subY = 0; subY < metaTileSizeY; ++subY ) {
						int indexNumber = ( y + subY - info.minY ) * ( info.maxX - info.minX ) + x + subX - info.minX;
						mapnik::image_view<mapnik::image_data_32> view = image.get_view( subX * m_settings.tileSize + m_settings.margin, subY * m_settings.tileSize + m_settings.margin, m_settings.tileSize, m_settings.tileSize );
						std::string result;
						if ( !m_settings.deleteTiles || info.index[( x + subX - info.minX ) + ( y + subY - info.minY ) * ( info.maxX - info.minX )].size == 1 ) {
							if ( m_settings.reduceColors )
								result = mapnik::save_to_string( view, "png256" );
							else
								result = mapnik::save_to_string( view, "png" );

							if ( m_settings.pngcrush ) {
								tempOut.open();
								tempOut.write( result.data(), result.size() );
								tempOut.flush();
								tempIn.open();
								pclose( popen( ( "pngcrush " + tempOut.fileName() + " " + tempIn.fileName() ).toUtf8().constData(), "r" ) );
								QByteArray buffer = tempIn.readAll();
								tempIn.close();
								tempOut.close();
								if ( buffer.size() != 0 && buffer.size() < ( int ) result.size() ) {
									saved += result.size() - buffer.size();
									result.assign( buffer.constData(), buffer.size() );
								}
							}
						}

						info.index[indexNumber].start = data.size();
						info.index[indexNumber].size = result.size();
						data += result;
					}
				}

				qint64 position;
#pragma omp critical
				{
					position = info.tilesFile->pos();
					info.tilesFile->write( data.data(), data.size() );

					metaTilesRendered++;
					tilesSkipped += skipped;
					pngcrushSaved += saved;
					qDebug() << "Mapnik Renderer: [" << zoom << "], thread" << threadID << ", metatiles:" << metaTilesRendered << "/" << tasks.size();
				}

				for ( int subX = 0; subX < metaTileSizeX; ++subX ) {
					for ( int subY = 0; subY < metaTileSizeY; ++subY ) {
						int indexNumber = ( y + subY - info.minY ) * ( info.maxX - info.minX ) + x + subX - info.minX;
						info.index[indexNumber].start += position;
开发者ID:Karry,项目名称:monavsailfish,代码行数:67,代码来源:mapnikrenderer.cpp

示例9: UtvPlatformGetSystemStats

/* UtvGetSystemStats
   Populates a CJSON struct with relevant system stats information
*/
UTV_RESULT UtvPlatformGetSystemStats( void* pVoidResponseData )
{
  UTV_RESULT result = UTV_OK;
  UTV_INT8 ubReadBuffer[1024];
  FILE* fpVmStat;
  UTV_UINT32 uiVmStatVer = 0;
  FILE* fp;
  UTV_UINT32 uiScanCount = 0;
  UTV_UINT32 uiMemFree = 0;
  UTV_UINT32 uiMemUsed = 0;
  UTV_UINT32 uiMemTotal = 0;
  UTV_UINT32 uiMemPercentUsed = 0;
  UTV_UINT32 uiCpuUser = 0;
  UTV_UINT32 uiCpuSystem = 0;
  UTV_UINT32 uiCpuTotalUsed = 0;
  cJSON* responseData = (cJSON*)pVoidResponseData;
  cJSON* memObject = NULL;
  cJSON* cpuObject = NULL;

  if (NULL != responseData)
  {
    memset(ubReadBuffer, 0x00, sizeof(ubReadBuffer));

    /* Get stats */
    fpVmStat = popen( "vmstat", "r" );

    if ( !fpVmStat )
    {
      result = UTV_FILE_OPEN_FAILS;
    }
    else
    {
      /* Parse first 2 headers... ignore this data */
      fgets( ubReadBuffer, sizeof(ubReadBuffer), fpVmStat );
      fgets( ubReadBuffer, sizeof(ubReadBuffer), fpVmStat );

      if ( 0 == strncmp( ubReadBuffer, " r  b  w", strlen( " r  b  w" ) ) )
      {
        uiVmStatVer = 2;
      }
      else if ( 0 == strncmp( ubReadBuffer, " r  b   swpd", strlen( " r  b   swpd" ) ) )
      {
        uiVmStatVer = 3;
      }

      /* Parse actual stats */
      fgets( ubReadBuffer, sizeof(ubReadBuffer), fpVmStat );

      if ( 2 == uiVmStatVer )
      {
        uiScanCount = sscanf( ubReadBuffer,
                              "%*u %*u %*u %*u %lu %*u %*u %*u %*u %*u %*u %*u %*u %lu %lu",
                              &uiMemFree,
                              &uiCpuUser,
                              &uiCpuSystem );
      }
      else if ( 3 == uiVmStatVer )
      {
        uiScanCount = sscanf( ubReadBuffer,
                              "%*u %*u %*u %lu %*u %*u %*u %*u %*u %*u %*u %*u %lu %lu",
                              &uiMemFree,
                              &uiCpuUser,
                              &uiCpuSystem );
      }

      if ( 3 != uiScanCount )
      {
        result = UTV_READ_FAILS;
      }
      else
      {
        /* Calculate total used CPU */
        uiCpuTotalUsed = uiCpuUser + uiCpuSystem;
      }
                      
      pclose( fpVmStat );
      fpVmStat = NULL;

      fp = fopen( "/proc/meminfo", "r" );

      if ( !fp )
      {
        result = UTV_FILE_OPEN_FAILS;
      }
      else
      {
        /* Parse lines */
        fgets( ubReadBuffer, sizeof(ubReadBuffer), fp );

        if ( 0 == sscanf( ubReadBuffer, "MemTotal: %lu", &uiMemTotal ) )
        {
          result = UTV_READ_FAILS;
        }
        else
        {
          /* Calculate memory percentage */
          if ( 0 != uiMemTotal )
//.........这里部分代码省略.........
开发者ID:TooLogic,项目名称:android_device_softwinner,代码行数:101,代码来源:platform-os-linux-getsystemstats.c

示例10: main

int main(int argc, char *argv[])
{
	int rtn;
	int v;

	FILE *fp;
	unsigned char b[S_BUF];
	char *tp;

	int i_port_no;
	int shtdwn;

	struct option long_opts[] = {
		{"input",	1, NULL, 0},
		{"time",	1, NULL, 1},
		{0, 0, 0, 0}
	};

	int res = 0;
	int idx = 0;

	while((res = getopt_long_only(argc, argv, "it", long_opts, &idx)) != EOD) {
		switch(res) {
		case 0:	/* input */
			DPRINT("input opt\n");
			DPRINT("name=%s val=%s\n",long_opts[idx].name, optarg);
			i_port_no = atoi(optarg);
			if(i_port_no == 0) { /* 0 : not number */
				fprintf(stderr, "Parameter not number : %s\n",optarg);
			}
			break;
		case 1: /* time */
			DPRINT("time opt\n");
			DPRINT("name=%s val=%s\n",long_opts[idx].name, optarg);
			shtdwn = atoi(optarg);
			if(shtdwn == 0) { /* 0 : not number */
				fprintf(stderr, "Parameter not number : %s\n",optarg);
			}
			break;
		case 'i':
		case 't':
			break;
		}
	}

	DPRINT("idx=%d\n",idx);

	if( argc == 1 ) {
		/* default */
		i_port_no = INPUT_PORT;
		shtdwn = SHTDWN;
	} else {
		if(idx == 0 || i_port_no == 0 || shtdwn == 0) {
			fprintf(stderr, "Usage:%s\n",CMDNAME);
			fprintf(stderr, "      %s --input <port No.> --time <shutdown>\n",CMDNAME);
			fprintf(stderr, "      %s --input=<port No.> --time=<shutdown>\n",CMDNAME);
			fprintf(stderr, "  (default:--input 24 --time 30)\n");
			return 1;
		}
	}

	/* No allow dup run */
	memset(b,0,S_BUF);
	DPRINT("PSNAME=%s\n",PSNAME);
	fp = popen(PSNAME, "r");
	if(fp == NULL) {
		fprintf(stderr, "fopen():Open Error.\n");
		return 1;
	} else {
		/*fgets(b, S_BUF, fp);*/
		fread(b, 1, S_BUF, fp);
		pclose(fp);
		DPRINT("val:\n%s",b);
		tp = strstr(b, CMDNAME);
		DPRINT("tp:\n%s",tp);
		DPRINT("strlen(tp)=%d\n",strlen(tp));
		if(strlen(tp) == strlen(CMDNAME)+1) {
			DPRINT("One Process running.\n");
		} else {
			/* No allow dup run */
			fprintf(stderr, "Two Processes running Error. Stop.\n");
			return 0;	/* normal */
		}
	}

	rtn = wiringPiSetupGpio();
	if( rtn == -1 ) {
		fprintf(stderr, "wiringPiSetupGpio(): Error (%d)\n", rtn);
		return 1;
	}

	pullUpDnControl(i_port_no, PUD_UP); /* pullup */
	pinMode(i_port_no, INPUT); 

	v = 0;  
	v = digitalRead(i_port_no);
	DPRINT("val=%d\n", v);

	/* SW ON */
	if(v == 0) {	/* 0=ON 1=OFF:because pullup */
//.........这里部分代码省略.........
开发者ID:k1segawa,项目名称:raspi,代码行数:101,代码来源:pwoff.c

示例11: pclose

 // dtor closes the pipe
 ~wxStdioPipe()
 {
     if ( m_fp )
         pclose(m_fp);
 }
开发者ID:erwincoumans,项目名称:wxWidgets,代码行数:6,代码来源:stackwalk.cpp

示例12: convert


//.........这里部分代码省略.........
                    fwrite (&size, 1, sizeof (size), temp_file);
                    header_written = 1;
                }

                int64_t res = fwrite (buffer, 1, sz, temp_file);
                if (sz != res) {
                    fprintf (stderr, "converter: write error (%lld bytes written out of %d)\n", res, sz);
                    goto error;
                }
            }
            if (abort && *abort) {
                goto error;
            }
            if (temp_file && temp_file != enc_pipe) {
                fseek (temp_file, wavehdr_size, SEEK_SET);
                fwrite (&outsize, 1, 4, temp_file);

                fclose (temp_file);
                temp_file = NULL;
            }

            if (encoder_preset->encoder[0] && encoder_preset->method == DDB_ENCODER_METHOD_FILE) {
                enc_pipe = popen (enc, "w");
            }
        }
    }
    err = 0;
error:
    if (temp_file && temp_file != enc_pipe) {
        fclose (temp_file);
        temp_file = NULL;
    }
    if (enc_pipe) {
        pclose (enc_pipe);
        enc_pipe = NULL;
    }
    if (dec && fileinfo) {
        dec->free (fileinfo);
        fileinfo = NULL;
    }
    if (abort && *abort && out[0]) {
        unlink (out);
    }
    if (input_file_name[0] && strcmp (input_file_name, "-")) {
        unlink (input_file_name);
    }

    // write junklib tags
    uint32_t tagflags = JUNK_STRIP_ID3V2 | JUNK_STRIP_APEV2 | JUNK_STRIP_ID3V1;
    if (encoder_preset->tag_id3v2) {
        tagflags |= JUNK_WRITE_ID3V2;
    }
    if (encoder_preset->tag_id3v1) {
        tagflags |= JUNK_WRITE_ID3V1;
    }
    if (encoder_preset->tag_apev2) {
        tagflags |= JUNK_WRITE_APEV2;
    }
    DB_playItem_t *out_it = deadbeef->pl_item_alloc ();
    deadbeef->pl_item_copy (out_it, it);
    deadbeef->pl_replace_meta (out_it, ":URI", out);
    deadbeef->pl_delete_meta (out_it, "cuesheet");

    deadbeef->junk_rewrite_tags (out_it, tagflags, encoder_preset->id3v2_version + 3, "iso8859-1");

    // write flac tags
开发者ID:Tydus,项目名称:deadbeef,代码行数:67,代码来源:converter.c

示例13:

KaldiStream::~KaldiStream() {
  if (_ffid) pclose(_ffid);
  if (_lfid) pclose(_lfid);
}
开发者ID:ZhouJiaLinmumu,项目名称:libdnn,代码行数:4,代码来源:data-io.cpp

示例14: wine_start

bool wine_start(char *wine_app, char *avsloader, AVS_PIPES *avs_pipes, int pipe_timeout)
{
  char sname[MAX_PATH];
  struct stat st;
  sprintf(sname, "%s %s %d", wine_app, avsloader, pipe_timeout);

  FILE *pfile = popen(sname, "r");
  if (!pfile)
  {
   DEBUG_PRINTF_RED("avsfilter : popen failed, errno %d, failed start app is : [%s]\n", errno, sname);
   return false;
  }

  if (fscanf(pfile, "%s\n", sname) != 1 ||
      stat(sname, &st) ||
      !S_ISDIR(st.st_mode))
  {
    DEBUG_PRINTF_RED("avsfilter : tmpdirname [%s] failed, errno %d[stat %d isdir %d]\n", sname, errno, stat(sname, &st), S_ISDIR(st.st_mode));
    pclose(pfile);
    return false;
  }

  DEBUG_PRINTF("avsfilter : good tmpdirname %s\n", sname);

  if (!init_pipes(avs_pipes, CMD_PIPE_NUM, pfile))
  {
    DEBUG_PRINTF_RED("init_pipes failed\n");
    pclose(pfile);
    return false;
  }

  time_t t = time(NULL);
  DEBUG_PRINTF("avsfilter : precreate thread time %s\n",
         ctime(&t));
  pthread_t thread;
  TPARSER tp = { avs_pipes, pfile };

  open_pipes_ok = false;

  if (pthread_create(&thread, NULL, parse_wine_stdout, &tp))
  {
    DEBUG_PRINTF_RED("Cannot pthread started...Errno %d\n",errno);
    deinit_pipes(avs_pipes, CMD_PIPE_NUM);
    return false;
  }

  t = time(NULL);
  DEBUG_PRINTF("avsfilter : preopen time %s\n",
         ctime(&t));

  if (!open_pipes(avs_pipes, CMD_PIPE_NUM) || wine_loader_down)
  {
    open_pipes_ok = true;
    DEBUG_PRINTF_RED("open_pipes failed\n");
    deinit_pipes(avs_pipes, CMD_PIPE_NUM);
    return false;
  }

  open_pipes_ok = true;

  if (pipe_test_filter (avs_pipes[PIPE_LOADER_READ].hpipe,
                        avs_pipes[PIPE_FILTER_WRITE].hpipe))
  {
    DEBUG_PRINTF("avsfilter : test pipe to filter ok\n");

    if (pipe_test_filter (avs_pipes[PIPE_LOADER_READ].hpipe,
                          avs_pipes[PIPE_LOADER_WRITE].hpipe))
    {
      DEBUG_PRINTF("avsfilter : test pipe to loader ok\n");
    }
    else
      goto error_pipe_test;
  }
  else
  {
    error_pipe_test:
    DEBUG_PRINTF_RED("Error test read/write pipes\n");
    deinit_pipes(avs_pipes, CMD_PIPE_NUM);
    return false;
  }

  DEBUG_PRINTF("wine start is ok\n");
  return true;
}
开发者ID:BackupTheBerlios,项目名称:avidemux-svn,代码行数:84,代码来源:avsfilter.cpp

示例15: get_suggested_omp_num_threads

int get_suggested_omp_num_threads() {

  int default_num_threads=1, suggested_num_threads=1;
  
  char* env_var_c;
  env_var_c = getenv ("OMP_NUM_THREADS");
  if(env_var_c) 
    {
      return atoi(env_var_c);
    }
  //    cout<<"OMP_NUM_THREADS is not defined"<<endl;
  
  //set number of threads for appropriate OS
  int avload, nbofproc=omp_get_num_procs();
  FILE *iff;
    
#if defined(__APPLE__) || defined(__MACH__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__bsdi__) || defined(__DragonFly__)
  cout<<"is MAC/*BSD"<<endl;
  iff= popen("echo $(sysctl -n vm.loadavg|cut -d\" \" -f2)", "r");
  if (!iff)
    {
      return default_num_threads;
    }
      
#elif defined(__linux__) || defined(__gnu_linux__) || defined(linux)
  iff= popen("cat /proc/loadavg |cut -d\" \" -f2", "r");
  if (!iff)
    {
      return default_num_threads;
    }
   
#elif defined (__unix) || (__unix__)
  iff=freopen("/proc/loadavg","r",stderr);
  fclose(stderr);
  if(!iff)
    {
      cout<<"your OS is not supported"<<endl;
      return default_num_threads;
    }
  iff= popen("cat /proc/loadavg 2>/dev/null|cut -d\" \" -f2", "r");
  if (!iff)
    {
      return default_num_threads;
    }

#elif defined(_WIN32) || defined(__WIN32__) || defined(__WINDOWS__)
  iff= popen("wmic cpu get loadpercentage|more +1", "r");
  if (!iff)
    {
      return default_num_threads;
    }
  char buffer[4];
  char* c;
  c=fgets(buffer, sizeof(buffer), iff);
  if(!c)
    {
      return default_num_threads;
    }
  pclose(iff);
  int cout=0;
  while(buffer[count]!='\0' && buffer[count]!=' ')count++;
  for(int i=1,j=1;i<=count;i++,j*=10)
    avload+=(buffer[count-i]-'0')*j;
  suggested_num_threads=nbofproc-(int)(avload*((float)nbofproc/100)+0.5);
  return suggested_num_threads;

#else 
  cout<<"Can't define your OS"<<endl;
  return default_num_threads;
#endif

  char buffer[4];
  char* c;
  c=fgets(buffer, sizeof(buffer), iff);
  if(!c)
    {
      return default_num_threads;
    }
  pclose(iff);
  avload=(buffer[0]-'0')+((buffer[2]-'0')>5?1:0);

  suggested_num_threads=nbofproc-avload;
  return suggested_num_threads;
}
开发者ID:nodarai,项目名称:rapport,代码行数:84,代码来源:set_num_threads.cpp


注:本文中的pclose函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。