[test@vm c]$ cat mynginx.c
#include <stdio.h> #include <string.h> #include <unistd.h> char **os_argv; char *os_argv_last; init_setproctitle(void) { char *p; size_t size; int i; size = 0; os_argv_last = os_argv[0]; for (i = 0; os_argv[i]; i++) { if (os_argv_last == os_argv[i]) { os_argv_last = os_argv[i] + strlen(os_argv[i]) + 1; } } os_argv_last += strlen(os_argv_last); } void setproctitle(char *title) { char *p; os_argv[1] = NULL; p = strncpy((char *) os_argv[0], (char *) title, strlen(title)); p += strlen(title); if (os_argv_last - (char *) p > 0) { memset(p, ' ', os_argv_last - (char *) p); } } void start_woker_processes() { setproctitle("mynginx:worker process"); for(;;) { sleep(1); printf("worker pid=%d\n",getpid()); } } void start_dispatcher_process() { setproctitle("mynginx:dispatcher process"); for(;;) { sleep(1); printf("\tdispatcher pid=%d\n",getpid()); } } void save_argv(int argc, char *const *argv) { os_argv = (char **) argv; } int main(int argc, char **argv) { int fd; int i; pid_t pid; save_argv(argc, argv); init_setproctitle(); printf("father pid1=%d\n",getpid()); for (i = 0; i <3; i++) { pid = fork(); if (pid == 0) { start_woker_processes(); } } pid = fork(); if (pid == 0) { start_dispatcher_process(); } printf("father pid2=%d\n",getpid()); while(1) sleep(1); return 0; }
make mynginx
./mynginx
ps -ef |grep mynginx 即可看到
test 20553 20463 0 23:54 pts/0 00:00:00 ./mynginx
test 20554 20553 0 23:54 pts/0 00:00:00 mynginx:worker process
test 20555 20553 0 23:54 pts/0 00:00:00 mynginx:worker process
test 20556 20553 0 23:54 pts/0 00:00:00 mynginx:worker process
test 20557 20553 0 23:54 pts/0 00:00:00 mynginx:dispatcher process
root 20574 20560 0 23:54 pts/2 00:00:00 grep mynginx