1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/gclib/spawn.c Tue Jan 24 23:57:11 2012 +0000
1.3 @@ -0,0 +1,84 @@
1.4 +#include <stdlib.h>
1.5 +#include <stdio.h>
1.6 +#ifndef WIN32
1.7 +#include <sys/wait.h>
1.8 +#endif
1.9 +#include <gclib/gclib.h>
1.10 +
1.11 +#define SPAWN_BUFSIZE 128
1.12 +
1.13 +boolean spawn_sync(char **argv,char **standard_output,int *exit_status)
1.14 +{
1.15 +/* Don't use g_spawn_sync on WIN32 for now to avoid needing the helper */
1.16 +#if HAVE_GLIB && !defined(WIN32)
1.17 + char *standard_error;
1.18 + GError *error=NULL;
1.19 + gboolean retval;
1.20 + GSpawnFlags flags=G_SPAWN_SEARCH_PATH;
1.21 + if (!standard_output)
1.22 + flags=G_SPAWN_STDOUT_TO_DEV_NULL;
1.23 + retval=g_spawn_sync(NULL,argv,NULL,flags,NULL,NULL,standard_output,
1.24 + &standard_error,exit_status,&error);
1.25 + fputs(standard_error,stderr);
1.26 + g_free(standard_error);
1.27 + if (!retval)
1.28 + {
1.29 + fprintf(stderr,"%s\n",error->message);
1.30 + g_error_free(error);
1.31 + }
1.32 + else if (exit_status)
1.33 + *exit_status=WEXITSTATUS(*exit_status);
1.34 + return retval;
1.35 +#else
1.36 + FILE *fp;
1.37 + int i,r;
1.38 + size_t n,len;
1.39 + String *command_line,*string;
1.40 + command_line=string_new(NULL);
1.41 + for(i=0;argv[i];i++)
1.42 + {
1.43 + if (i)
1.44 + string_append_c(command_line,' ');
1.45 + string_append(command_line,argv[i]);
1.46 + }
1.47 + fp=popen(command_line->str,"r");
1.48 + string_free(command_line,TRUE);
1.49 + if (!fp)
1.50 + {
1.51 + perror(command_line->str);
1.52 + return FALSE;
1.53 + }
1.54 + string=string_new(NULL);
1.55 + do
1.56 + {
1.57 + len=string->len;
1.58 + string_set_size(string,len+SPAWN_BUFSIZE);
1.59 + n=fread(string->str+len,1,SPAWN_BUFSIZE,fp);
1.60 + if (n<0)
1.61 + {
1.62 + perror("fread");
1.63 + (void)pclose(fp);
1.64 + string_free(string,TRUE);
1.65 + return FALSE;
1.66 + }
1.67 + string_set_size(string,len+n);
1.68 + } while(n);
1.69 + r=pclose(fp);
1.70 + if (r<0)
1.71 + {
1.72 + perror("pclose");
1.73 + string_free(string,TRUE);
1.74 + return FALSE;
1.75 + }
1.76 + else
1.77 + {
1.78 + if (exit_status)
1.79 + *exit_status=r;
1.80 + if (standard_output)
1.81 + *standard_output=string_free(string,FALSE);
1.82 + else
1.83 + string_free(string,TRUE);
1.84 + return TRUE;
1.85 + }
1.86 +#endif
1.87 +}