看一下这个代码片段,再次展现了linux的严谨,既考虑了linux, 也考虑了 APPLE
- #if __linux__
- if (!(tmp = strdup(program_invocation_name)))
- goto syerr;
-
- program_invocation_name = tmp;
-
- if (!(tmp = strdup(program_invocation_short_name)))
- goto syerr;
-
- program_invocation_short_name = tmp;
- #elif __APPLE__
- if (!(tmp = strdup(getprogname())))
- goto syerr;
-
- setprogname(tmp);
- #endif
-
- /* Now make a full deep copy of the environment and argv[] */
- if ((error = spt_copyenv(envc, envp)))
- goto error;
-
- if ((error = spt_copyargs(argc, argv)))
- goto error;
-
- SPT.nul = nul;
- SPT.base = base;
- SPT.end = end;
-
- return;
- syerr:
- error = errno;
- error:
- SPT.error = error;
- } /* spt_init() */
-
-
- #ifndef SPT_MAXTITLE
- #define SPT_MAXTITLE 255
- #endif
-
- void setproctitle(const char *fmt, ...) {
- char buf[SPT_MAXTITLE + 1]; /* use buffer in case argv[0] is passed */
- va_list ap;
- char *nul;
- int len, error;
-
- if (!SPT.base)
- return;
-
- if (fmt) {
- va_start(ap, fmt);
- len = vsnprintf(buf, sizeof buf, fmt, ap);
- va_end(ap);
- } else {
- len = snprintf(buf, sizeof buf, "%s", SPT.arg0);
- }
-
- if (len <= 0)
- { error = errno; goto error; }
-
- if (!SPT.reset) {
- memset(SPT.base, 0, SPT.end - SPT.base);
- SPT.reset = 1;
- } else {
- memset(SPT.base, 0, spt_min(sizeof buf, SPT.end - SPT.base));
- }
-
- len = spt_min(len, spt_min(sizeof buf, SPT.end - SPT.base) - 1);
- memcpy(SPT.base, buf, len);
- nul = &SPT.base[len];
-
- if (nul < SPT.nul) {
- *SPT.nul = '.';
- } else if (nul == SPT.nul && &nul[1] < SPT.end) {
- *SPT.nul = ' ';
- *++nul = '\0';
- }
-
- return;
- error:
- SPT.error = error;
- } /* setproctitle() */
-
-
- #endif /* __linux || __APPLE__ */
- #endif /* !HAVE_SETPROCTITLE */
-
- #ifdef SETPROCTITLE_TEST_MAIN
- int main(int argc, char *argv[]) {
- spt_init(argc, argv);
-
- printf("SPT.arg0: [%p] '%s'\n", SPT.arg0, SPT.arg0);
- printf("SPT.base: [%p] '%s'\n", SPT.base, SPT.base);
- printf("SPT.end: [%p] (%d bytes after base)'\n", SPT.end, (int) (SPT.end - SPT.base));
- return 0;
- }
- #endif