进程编程听课笔记

[size=x-large]1. 获取ID[/size]

#include <sys/types.h>
#include <unistd.h>

pid_t getpid(void) //获取本进程ID
pid_t getppid(void) //获取父进程ID


[size=x-large]2. 创建子进程[/size]
[size=medium]fork[/size]

#include <unistd.h>
pid_t fork(void)

调用一次,返回两次,三种返回值
父进程中,fork返回子进程的PID
子进程中,fork返回0
出现错误,返回负值

子进程复制父进程的数据空间和堆栈空间, 从fork之后执行代码

[size=medium]vfork:[/size]

#include <sys/types.h>
#include <unistd.h>

pid_t vfork(void)


区别:
fork: 子进程[color=red]复制[/color]父进程的数据段
vfork: 子进程[color=red]共享[/color]父进程的数据段

fork: 父子进程的执行顺序不去诶的那个
vfork: 子进程先运行, 父进程后运行

[size=medium]system[/size]

#include <stdlib.h>

int system(const char *string)

[color=red]调用fork产生子进程[/color], 由子进程调用/bin/sh -c string 来执行参数string所代表的命令

例如:

#include <stdlib.h>

main()
{
system("ls -al /etc/passwd")
}


[size=x-large]3. exec函数族[/size]
[color=red]exec启动新程序, 替换原有的进程, PID不变[/color]
[size=medium]execl[/size]

#include <unistd.h>
int execl(const char *path, const char *arg1,...)

path: 新程序所在路径([color=red]完整路径[/color])
arg: 新程序的参数,[color=red]arg1为程序名,以空指针NULL结束[/color]
例如:

#include <unistd.h>

main()
{
execl("/bin/ls", "ls", "-al" , "/etc/passwd", (char *)0);
}



[size=medium]execlp[/size]

#include <unistd.h>
int execl(const char *path, const char *arg1,...)

path: 被执行的程序名,[color=red]不含路径, 从path环境变量中查找[/color]
其他参数同execl
例如:

#include <unistd.h>

main()
{
execlp("ls", "ls", "-al" , "/etc/passwd", (char *)0);
}


[size=medium]execv[/size]

#include <unistd.h>

int execv(const char *path, char *const argv[])

path: 被执行的程序名([color=red]含完整路径[/color])
argv[]: 命令行参数数组

例如:

#include <unistd.h>

main()
{
char *argv[]={"ls" , "-al", "/etc/passwd", (char *)0};
execl("/bin/ls",argv);
}



[size=x-large]4.进程等待[/size]
wait

#include <sys/types.h>
#include <sys/wait.h>

pid_t wait(int *status)


阻塞该进程,知道其[color=red]某个[/color]子进程退出

//父进程必然在子进程之后输出
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

void main(){
pid_t pc, pr;
pc=fork();
if(pc==0){//子进程
printf("This is child process with PID %d\n", getpid());
sleep(5);
}else if(pc >0){//父进程
pr=wait(NULL);//等待
printf("I catch a childe process with PID of %d\n", pr);
}
exit(0);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值