course:nctu-網路程式設計:chapter1
UNIX
0x00 Outline
- Programs
- Processes
- File Model
- Signal Model
- Process Control
0x01 Programs
Start-up Function and Environment List
- argc : 參數個數
- argv : 參數陣列,index 0 的參數為程式名稱本身
- envp : 環境變數
- extern : 可以聲明變數會在其他的位置(檔案)被定義
extern 宣告不能直接指定值,會發生重複定義的錯誤
extern double some_var = 100; [X]
extern double some_var; [O]
some_var = 100;
#include<stdio.h> #include<stdlib.h> int main(int argc,char *argv[], char *envp[]) { int i; for(i=0; envp[i] != (char *) 0 ;i++) { printf("%s\n",envp[i]); } exit(0); }
#include<stdio.h> #include<stdlib.h> int main(int argc,char *argv[]) { extern char **environ; int i; for(i=0; environ[i] != (char *) 0 ;i++) { printf("%s\n",environ[i]); } exit(0); }
0x02 Process
提到 process 首先要了解一下程式執行時的記憶體分配狀況
這邊可以參考在修高等 UNIX 程式設計時的筆記 Process Environment:Memory Layout
#include<stdio.h> #include<stdlib.h> #include<string.h> int debug=1; /* Initialized data segment */ char *progname; /* Uninitialized data segment */ int main(int argc, char *argv[]) { int i; /* Stack */ char *ptr; /* Stack */ progname = argv[0]; printf("argc = %d\n",argc); for(i = 1; i < argc; i++) { ptr = malloc(strlen(argv[i]) + 1); /* Heap */ strcpy(ptr, argv[i]); if(debug) { printf("%s\n",ptr); } } }
每個 Process 也會有 Process ID,不同系統間可能有差異,但大致如下
- 0: a special kernel process for “scheduler”.
- 1: a special process,called “init”.
- 2: a kernel process, called “pagedaemon”.
- 3 ~ (232-1) : no special meaning.
User and Group
執行 process 時也會有使用者身份和群組的權限問題
這部分可參考 SUID & SGID in UNIX
#include <unistd.h> #include <sys/types.h> uid_t getuid(void); /* returns the real user ID of the calling process. */ uid_t geteuid(void); /* returns the effective user ID of the calling process. */ gid_t getgid(void); /* returns the real group ID of the calling process. */ gid_t getegid(void); /* returns the effective group ID of the calling process. */
#include <sys/types.h> #include <pwd.h> struct passwd *getpwnam(const char *name); struct passwd *getpwuid(uid_t uid); struct passwd { char *pw_name; /* username */ char *pw_passwd; /* user password */ uid_t pw_uid; /* user ID */ gid_t pw_gid; /* group ID */ char *pw_gecos; /* user information */ char *pw_dir; /* home directory */ char *pw_shell; /* shell program */ };
course/nctu-網路程式設計/chapter1.txt · 上一次變更: 由 127.0.0.1