Search code examples
clinuxsolarisstderrsunos

how do "system()" without message on stderr on SunOS


I'm trying to figure out how to do a system() function call (in C) on SunOS and NOT have anything printed to stderr (or stdout). Currently, the following code compiles/runs on Linux, OSX, HP-UX, and SunOS. On all but SunOS, I get a nice output of something like:

i = 32512 (0x7f00); wexitstatus = 127

But, on SunOS I get:

sh: unknowncommand: not found
i = 256 (0x100); wexitstatus = 1

...that extra "sh:" line is annoying :)

(My goal: quiet programmatic determination of whether or not I can do "cc" and/or "gcc" commands.)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>

int main (int argc, char **argv)
{
int i;

char buf [1000];

strcpy (buf, "unknowncommand -c foo.c > /dev/null 2>&1");

i = system (buf);

printf ("i = %d (0x%x); wexitstatus = %d\n", i, i, WEXITSTATUS (i));

return 0;
}

Solution

  • The which command will find an executable that lives in your PATH variable.

    which gcc
    which cc
    

    you can use this in your system call.

    This is a poor man's version of which:

    // performs task similar to which command
    // mywhich.c
    char **split(char **result, char *w, const char *src, const char *delim)
    {
        char *p;
        w=strdup(src);
        int i=0;
        for(p=strtok(w, delim); p!=NULL; p=strtok(NULL, delim))
        {
           result[i++]=p;
           result[i]=NULL;
        }
        return result;
    }
    
    char *detect_cc(char *cc, char **argv)
    {
        char search[PATH_MAX]={0x0};
        char resolved[PATH_MAX]={0x0};
    
        char *w=NULL;
        int i=0,j=0;
        char *result[1024]={NULL};      // set 1024 to appropriate value
        char *PATH=getenv("PATH");
    
        *cc=0x0;
        split(result, w, PATH, ":");
        for(i=0 ; !*cc && result[i]!=NULL; i++)
        {
            for(j=0; argv[j]!=NULL; j++)
            {
               sprintf(search,"%s/%s", result[i], argv[j]);
    
               if(realpath(search, resolved)!=NULL)
               {    
                  if(access(resolved, X_OK)==0)
                     strcpy(cc, resolved);
               }  
            }
        }
        free(w);
        return cc;
    }
    
    
    int main(int argc, char **argv)
    {
       char cc[PATH_MAX]={0x0};
       argv++;
       detect_cc(cc, argv);
       if(*cc)
         printf("found: %s\n", cc);
       else
         printf("Not found in PATH\n");
    
       return 0;  
    }
    

    usage:

     ./mywhich  gcc cc foo
    

    It stops on the first file found. Doctor the code to suppress messages as you see fit.