您的位置:首页 > 运维架构 > Linux

【Linux系统学习】进程与线程

2018-09-11 15:52 183 查看

进程运行新程序

fork()/exec()组合是典型的Linux新进程产生模式,通常先用`fork()`创建新进程,然后新进程通过调用`exec()类`执行自己的任务。
exec(),将一个可执行程序文件读入,代替原先的程序执行。此时,系统吧代码段替换成新程序的代码,废弃原有的数据段和堆栈段,并为新程序分配新的数据段与堆栈段,位移留下的就是进程号。
函数原型
#include<unistd.h>
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 execve(const char *filename, char *const argv[], char *const envp[]);
int execvp(const char *file, char *const argv[]);

execlptest.c

#include<errno.h>
#include<string.h>
#include<stdio.h>
#include<error.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>

char command[256];

int main(int argc, char **argv[])
{
int rtn;
while(1)
{
printf(">");
fgets(command, 256, stdin);
command[strlen(command)-1]=0;
if(fork()==0){
execlp(command, command);
perror(command);
exit(-1);
}else{
wait(&rtn);
printf("child process return %d\n", rtn);
}
}
return 0;
}

进程等待

wait()函数

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: