bl/spawn.c
author ali <ali@juiblex.co.uk>
Fri Jan 27 16:18:02 2012 +0000 (2012-01-27)
changeset 6 faab25d520dd
parent 5 f600b0d1fc5d
child 7 721e468c10f3
permissions -rw-r--r--
Rely on glib being available everywhere
     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 {
    12 /* Don't use g_spawn_sync on WIN32 for now to avoid needing the helper */
    13 #ifndef WIN32
    14     char *standard_error;
    15     GError *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     fputs(standard_error,stderr);
    23     g_free(standard_error);
    24     if (!retval)
    25     {
    26 	fprintf(stderr,"%s\n",error->message);
    27 	g_error_free(error);
    28     }
    29     else if (exit_status)
    30 	*exit_status=WEXITSTATUS(*exit_status);
    31     return retval;
    32 #else
    33     FILE *fp;
    34     int i,r;
    35     size_t n,len;
    36     GString *command_line,*string;
    37     command_line=g_string_new(NULL);
    38     for(i=0;argv[i];i++)
    39     {
    40 	if (i)
    41 	    g_string_append_c(command_line,' ');
    42 	g_string_append(command_line,argv[i]);
    43     }
    44     fp=popen(command_line->str,"r");
    45     g_string_free(command_line,TRUE);
    46     if (!fp)
    47     {
    48 	perror(command_line->str);
    49 	return FALSE;
    50     }
    51     string=g_string_new(NULL);
    52     do
    53     {
    54 	len=string->len;
    55 	g_string_set_size(string,len+SPAWN_BUFSIZE);
    56 	n=fread(string->str+len,1,SPAWN_BUFSIZE,fp);
    57 	if (n<0)
    58 	{
    59 	    perror("fread");
    60 	    (void)pclose(fp);
    61 	    g_string_free(string,TRUE);
    62 	    return FALSE;
    63 	}
    64 	g_string_set_size(string,len+n);
    65     } while(n);
    66     r=pclose(fp);
    67     if (r<0)
    68     {
    69 	perror("pclose");
    70 	g_string_free(string,TRUE);
    71 	return FALSE;
    72     }
    73     else
    74     {
    75 	if (exit_status)
    76 	    *exit_status=r;
    77 	if (standard_output)
    78 	    *standard_output=g_string_free(string,FALSE);
    79 	else
    80 	    g_string_free(string,TRUE);
    81 	return TRUE;
    82     }
    83 #endif
    84 }