Determine OS during runtime

天涯浪子 提交于 2019-12-07 01:48:44

问题


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.


回答1:


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()




回答2:


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




回答3:


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.




回答4:


The accepted answer states uname, but doesn't provide a minimal working example, so here it is for anyone interested-hope it will save you the time it took for me:

#include <stdio.h>
#include <stdlib.h>
#include <sys/utsname.h>

int main(void) {
   struct utsname buffer;
   if (uname(&buffer) != 0) {
      perror("uname");
      exit(0);
   }
   printf("OS: %s\n", buffer.sysname);

   return 0;
}

(Possible) Output:

OS: Linux

PS: Unfortunately, this uses a POSIX header: Compilation fails due to missing file sys/utsname.h, which most probably won't work in Windows.




回答5:


if (strchr(getenv("PATH"),'\\'))
    puts("You may be on windows...");

Even do I agree that "Runtime isn't the time to determine this..."



来源:https://stackoverflow.com/questions/8706958/determine-os-during-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!