--- id: cf7cfd71-d2ac-4f5a-a175-808ef410a339 slug: linux-process-learning-2 title: Linux 进程学习 二 summary: "" status: published tags: [] cover: "" version: 1 slug_source: manual slug_locked: true published_at: "2022-10-16T16:13:33+08:00" created_at: "2022-10-16T16:13:33+08:00" updated_at: "2026-01-07T18:10:43+08:00" --- ## 创建进程 在 Linux 中每个进程都是父进程创建的,Linux 启动时会创建init 进程,这是系统的第一个进程,其 PID 为 1。 在 C 语言中,我们可以用fork函数创建新的进程: ```c #include pid_t fork(void); ``` - If fork() returns a negative value, the creation of a child process was unsuccessful. - fork() returns a zero to the newly created child process. - fork() returns a positive value, the process ID of the child process, to the parent. The returned process ID is of type pid_t defined in sys/types.h. Normally, the process ID is an integer. Moreover, a process can use function getpid() to retrieve the process ID assigned to this process. 也就是: > On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set to indicate the error. 也就是: - 返回负数,创建失败 - 返回 0 ,就是子进程,它永远返回 0 - 返回大于 0 的整数,这是父进程,它会返回子进程的pid ## 终止进程