bl/spawn.c
author ali <ali@juiblex.co.uk>
Fri Jan 27 21:40:35 2012 +0000 (2012-01-27)
changeset 7 721e468c10f3
parent 6 faab25d520dd
child 9 6a13fe0fc19e
permissions -rw-r--r--
Add support for non-ASCII testcases
     1 #include <stdlib.h>
     2 #include <stdio.h>
     3 #ifndef WIN32
     4 #include <sys/wait.h>
     5 #endif
     6 #include <bl/bl.h>
     7 
     8 #define SPAWN_BUFSIZE	128
     9 
    10 gboolean spawn_sync(char **argv,char **standard_output,int *exit_status,
    11   GError **error)
    12 {
    13 /* Don't use g_spawn_sync on WIN32 for now to avoid needing the helper */
    14 #ifndef WIN32
    15     char *standard_error=NULL;
    16     gboolean retval;
    17     GSpawnFlags flags=G_SPAWN_SEARCH_PATH;
    18     if (!standard_output)
    19 	flags=G_SPAWN_STDOUT_TO_DEV_NULL;
    20     retval=g_spawn_sync(NULL,argv,NULL,flags,NULL,NULL,standard_output,
    21       &standard_error,exit_status,error);
    22     if (standard_error)
    23 	fputs(standard_error,stderr);
    24     g_free(standard_error);
    25     if (retval && exit_status)
    26 	*exit_status=WEXITSTATUS(*exit_status);
    27     return retval;
    28 #else
    29     FILE *fp;
    30     int i,r;
    31     size_t n,len;
    32     GString *command_line,*string;
    33     command_line=g_string_new(NULL);
    34     for(i=0;argv[i];i++)
    35     {
    36 	if (i)
    37 	    g_string_append_c(command_line,' ');
    38 	g_string_append(command_line,argv[i]);
    39     }
    40     fp=popen(command_line->str,"r");
    41     g_string_free(command_line,TRUE);
    42     if (!fp)
    43     {
    44 	g_set_error(error,G_FILE_ERROR,g_file_error_from_errno(errno),
    45 	  "%s: %s",command_line->str,g_strerror(errno));
    46 	return FALSE;
    47     }
    48     string=g_string_new(NULL);
    49     do
    50     {
    51 	len=string->len;
    52 	g_string_set_size(string,len+SPAWN_BUFSIZE);
    53 	n=fread(string->str+len,1,SPAWN_BUFSIZE,fp);
    54 	if (n<0)
    55 	{
    56 	    g_set_error(error,G_FILE_ERROR,g_file_error_from_errno(errno),
    57 	      "Error reading from bookloupe: %s",g_strerror(errno));
    58 	    (void)pclose(fp);
    59 	    g_string_free(string,TRUE);
    60 	    return FALSE;
    61 	}
    62 	g_string_set_size(string,len+n);
    63     } while(n);
    64     r=pclose(fp);
    65     if (r<0)
    66     {
    67 	g_set_error(error,G_FILE_ERROR,g_file_error_from_errno(errno),
    68 	  "Error reading from bookloupe: %s",g_strerror(errno));
    69 	g_string_free(string,TRUE);
    70 	return FALSE;
    71     }
    72     else
    73     {
    74 	if (exit_status)
    75 	    *exit_status=r;
    76 	if (standard_output)
    77 	    *standard_output=g_string_free(string,FALSE);
    78 	else
    79 	    g_string_free(string,TRUE);
    80 	return TRUE;
    81     }
    82 #endif
    83 }