fork()
- 创建子进程。失败返回-1,子进程返回0,父进程返回子进程的PID
#include <sys/types.h>
#include <unistd.h>
pid_t fork();
getpid() getppid()
#include <sys/types.h>
#include <unistd.h>
pid_t getpid();
pit_t getppid();
- 父进程要得到子进程的ID只能记录fork()的返回值
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main() {
printf("%s\n", "我是鸣人!");
int pid = fork();
if (pid != 0) {
int status;
int result = wait(&status);
if (result == -1 || status != 0) {
printf("%s\n", "可恶,又失败了,再来一次!");
return -1;
} else {
printf("%s\n", "我负责性质变化!");
}
} else {
int second_pid = fork();
if (second_pid != 0) {
int new_status;
int new_result = waitpid(-1, &new_status, 0);
if (new_result == -1 || new_status != 0) {
exit(-1);
} else {
printf("%s\n", "我负责形态变化!");
exit(0);
}
} else {
printf("%s\n", "我负责产生查克拉!");
exit(0);
}
}
return 0;
}
我是鸣人!
我负责产生查克拉!
我负责形态变化!
我负责性质变化!
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int cnt = 0;
int main() {
int pid = fork();
if (pid) {
wait(NULL);
printf("[pid!=0:%d].", cnt);
return 0;
}
cnt++;
int pid2 = fork();
if (pid2) {
wait(NULL);
printf("[pid2!=0:%d],", cnt);
exit(0);
} else {
char** argv = (char**)malloc(sizeof(char *) * 3);
argv[0] = "echo", argv[1] = "Hello!", argv[2] = NULL;
int pid3 = fork();
cnt++;
if (pid3) {
free(argv);
wait(NULL);
printf("[pid3!=0:%d],", cnt);
exit(0);
} else {
cnt++;
execvp("echo", argv);
printf("Count %d,", cnt);
free(argv);
exit(0);
}
}
return 0;
}
Hello!
[pid3!=0:2],[pid2!=0:1],[pid!=0:0].
- exec函数族
具有在现有的进程中打开某-一可执行文件、覆盖现有程序执行的功能
只有失败返回-1
#inclde <unistd.h>
extern char **environ;
int execl(const char* path, const char* arg, ...);
int execlp(const char* file, const char* arg, ...);
int execle(const char* path, const char* arg, ..., char* const envp[]);
int execv(const char* path, char* const argv[]);
int execvp(const char* file, char* const argv[]);
int execvpe(const char* filename, char* const argv[], char* const envp[]);
int execve(const char* filename, char* const argv[], char* const envp[]);
- 我们可以将这些函数表示为: “exec + /v + p/e/pe”,所以这六个函数主要有两处不同。第一处不同(Iv) 在参数中表现为
“execl"类函数将所有参数作为-整个字符串代入,而"execv"类函数将 参数分别放入-一个字符串的数组中,将数组作为参数代入函数运行。第二处不同(p/e/pe) 表现为包含p (代表path)的函数可以模仿计算机中壳的功能,在"file"中不含”/"时应用环境变量PATH中的目录来寻找可执行文件,而包含e (代表environment)的函数可以像execve一样将"变量=数值"对作为环境变量代入程序。 - 可变参数最后一个为NULL
- getenv() setenv() unsetenv()
#include <stdlib.h>
extern char **environ;
char *getenv(const char *name);
int setenv(const char *name, const char *value, int rewrite);
void unsetenv(const char *name);