创建子进程
一个现有进程通过调用fork()创建子进程
子进程是父进程的副本
子进程获得父进程的数据空间,堆栈的副本
子进程复制父进程的缓冲区
父子进程共享内容
父进程和子进程共享正文段
父子进程相同的打开描述符共享一个文件表项
函数fork()
函数原型
#include <unistd.h>
pid_t
fork(void);
返回值说明
函数调用一次返回两次,子进程的返回值为0,父进程的返回值为子进程的进程id
函数失败时,父进程的返回值是-1
函数wait(),waitpid()
当进程正常或异常终止会向其父进程发送SIGCHLD信号
调用wait会导致进程阻塞,waitpid有一个选项可以使调用者不阻塞
waitpid有若干选项可以控制所要等待的进程
函数原型
#include <sys/wait.h>
pid_t
wait(int *stat_loc);
pid_t
waitpid(pid_t pid, int *stat_loc, int options);
参数说明,返回值说明
- 参数
stat_loc如果非空,则进程的终止状态存放刀stat_loc空间中
pid == -1 等待任一子进程,此时相当于wait
pid > 0 等待pid为pid的进程
pid == 0 等待组id等于调用进程组id的任意子进程
pid < 0 等待组id等于pid绝对值的任意进程
- 返回值
成功返回进程id,失败返回0
函数exec族
作用:exec族函数,用磁盘上的新程序替代当前进程的正文段,数据段,堆栈
- 函数原型
#include <unistd.h>
extern char **environ;
int
execl(const char *path, const char *arg0, ... /*, (char *)0 */);
int
execle(const char *path, const char *arg0, ...
/*, (char *)0, char *const envp[] */);
int
execlp(const char *file, const char *arg0, ... /*, (char *)0 */);
int
execv(const char *path, char *const argv[]);
int
execvp(const char *file, char *const argv[]);
int
execvP(const char *file, const char *search_path, char *const argv[]);
其他
getpid
getppid
getgid
getuid
测试程序
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main()
{
pid_t cliId;
char buf[100]="hello";
cliId = fork();
if(cliId == 0){
printf("%d : this is child",getpid());
printf("%d : get buf from father:%s\n",getpid(),buf);//子进程获得父进程栈
strcpy(buf,"nihao");//子进程修改自己的buf
} else{
printf("%d : child id is %d\n",getpid(),cliId);//父进程fork返回值为子进程pid
}
printf("%d : buf is %s\n",getpid(),buf);//观察buf输出与pid关系
sleep(100);
return 0;
}
本内容为个人学习内容,如有不正请指正,与诸君共勉
学习unp第二天