bl/spawn.c
author ali <ali@juiblex.co.uk>
Fri Jan 27 10:30:16 2012 +0000 (2012-01-27)
changeset 5 f600b0d1fc5d
parent 0 gclib/spawn.c@c2f4c0285180
child 6 faab25d520dd
permissions -rw-r--r--
Rename to bookloupe
     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 boolean 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 #if HAVE_GLIB && !defined(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     String *command_line,*string;
    37     command_line=string_new(NULL);
    38     for(i=0;argv[i];i++)
    39     {
    40 	if (i)
    41 	    string_append_c(command_line,' ');
    42 	string_append(command_line,argv[i]);
    43     }
    44     fp=popen(command_line->str,"r");
    45     string_free(command_line,TRUE);
    46     if (!fp)
    47     {
    48 	perror(command_line->str);
    49 	return FALSE;
    50     }
    51     string=string_new(NULL);
    52     do
    53     {
    54 	len=string->len;
    55 	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 	    string_free(string,TRUE);
    62 	    return FALSE;
    63 	}
    64 	string_set_size(string,len+n);
    65     } while(n);
    66     r=pclose(fp);
    67     if (r<0)
    68     {
    69 	perror("pclose");
    70 	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=string_free(string,FALSE);
    79 	else
    80 	    string_free(string,TRUE);
    81 	return TRUE;
    82     }
    83 #endif
    84 }