abkds
abkds

Reputation: 1794

Determine `OSTYPE` during runtime in C program

In a C program, I need to find the OSTYPE during runtime, on the basis of which I will do some operations.

Here is the code

#include <stdlib.h>
#include <string.h>

int main () {
    const char * ostype = getenv("OSTYPE");
    if (strcasecmp(ostype, /* insert os name */) == 0) ... 
    return 0;
}

But getenv returns NULL (and there is segmentation fault). When I do a echo $OSTYPE in the terminal it prints darwin15 . But when I do env | grep OSTYPE nothing gets printed, which means it is not in the list of environment variables. To make it work on my local machine I can go to the .bash_profile and export the OSTYPE manually but that doesn't solve the problem if I want to run a generated executable on a new machine.

Why is OSTYPE available while running terminal, but apparently not there in the list of environment variables. How to get around this ?

Upvotes: 1

Views: 455

Answers (1)

AlbusMPiroglu
AlbusMPiroglu

Reputation: 653

For the crash, you should check if the return was NULL or not before using it in strcmp or any function. From man 3 getenv:

The getenv() function returns a pointer to the value in the environment, or NULL if there is no match.

If you're at POSIX (most Unix's and somehow all Linux's), I agree with Paul's comment on uname.

But actually you can check for OSTYPE at compile time with precompiler (with #ifdef's), here's a similar question on so: Determine OS during runtime

Edit: uname

Good point Jonathan. man 2 uname on my linux tells how to use (and begin POSIX, macos has the same header, too):

SYNOPSIS

   #include <sys/utsname.h>

   int uname(struct utsname *buf);

DESCRIPTION uname() returns system information in the structure pointed to by buf. The utsname struct is defined in :

       struct utsname {
           char sysname[];    /* Operating system name (e.g., "Linux") */
           char nodename[];   /* Name within "some implementation-defined
                                 network" */
           char release[];    /* Operating system release (e.g., "2.6.28") */
           char version[];    /* Operating system version */
           char machine[];    /* Hardware identifier */
       #ifdef _GNU_SOURCE
           char domainname[]; /* NIS or YP domain name */
       #endif
       };

Upvotes: 0

Related Questions