Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine OS during runtime

Neither ISO C nor POSIX offer functionality to determine the underlying OS during runtime. From a theoretical point of view, it doesn't matter since C offers wrappers for the most common system calls, and from a nit-picking point of view, there doesn't even have to be an underlying OS.

However, in many real-world scenarios, it has proven helpful to know more about the host environment than C is willing to share, e.g. in order to find out where to store config files or how to call select(), so:

Is there an idiomatic way for an application written in C to determine the underlying OS during runtime?

At least, can I easily decide between Linux, Windows, BSD and MacOS?

My current guess is to check for the existence of certain files/directories, such as C:\ or /, but this approach seems unreliable. Maybe querying a series of such sources may help to establish the notion of "OS fingerprints", thus increasing reliability. Anyway, I'm looking forward to your suggestions.

like image 979
Philip Avatar asked Jan 03 '12 01:01

Philip


3 Answers

Actually, most systems have a uname command which shows the current kernel in use. On Mac OS, this is usually "Darwin", on Linux it's just plain "Linux", on Windows it's "ERROR" and FreeBSD will return "FreeBSD".

More complete list of uname outputs

I'm pretty sure that there's a C equivalent for uname, so you won't need system()

like image 78
Tom van der Woerdt Avatar answered Nov 18 '22 20:11

Tom van der Woerdt


IF you are on a POSIX system, you can call uname() from <sys/utsname.h>.

This obviously isn't 100% portable, but I don't think there will be any method that can grant that at runtime.

see the man page for details

like image 4
rejj Avatar answered Nov 18 '22 19:11

rejj


Runtime isn't the time to determine this, being that without epic kludges binaries for one platform won't run on another, you should just use #ifdefs around the platform sensitive code.

like image 1
richo Avatar answered Nov 18 '22 21:11

richo