进程替换

来源:互联网 发布:线刷用什么软件 编辑:程序博客网 时间:2024/06/09 19:00

进程替换:exec系列函数
何为进程替换: 一个运行的进程通过某种方式, 用磁盘上存储的程序(可执行文件)

原进程的所有的指令和数据。
int execl(char *pathfile, char *argv1, char*argv2, .... , (char*)0);
int execv(char *pathfile, char *argv[]);
execle(const char *path,const char *arg,...,char *const,envp[]);
execve(const char *filename,char *const argv[],char *const envp[]);
execlp
execvp(const char *file,char *const argvp[]);

练习题:
1exec进程启动输出“。。。。”,sleep 2秒,fork生成子进程, 子进程调用可执行
程序
main, 父进程输出“father start”, 然后sleep 3秒, 输出“father over”;main程序输
出传递给主函数的参数。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <signal.h>
int main(int argc, char *argv[])
{
 printf("mykill pid == %d\n", getpid());
 if(argc < 2)
 {
  printf("please input pid\n");
  exit(0);
 }
 //argv[1] = "1234";
 int pid = 0;
 sscanf(argv[1], "%d", &pid);
 printf("pid == %d\n", pid);
 if(kill(pid, SIGCHLD) == -1)
 {
  perror(NULL);
  exit(0);
 }
}

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
void main()
{
 printf("exec start\n");
 sleep(2);
 printf("exec front pid == %d\n", getpid());
 execl("./mykill", "./mykill", (char *)0);
 printf("exec finish\n");
 sleep(2);
 printf("exec end\n");
}


写时拷贝技术:
fork产生子进程时, 并不会完全复制其父进程。 内核将父进程的所有空间设置为只读,
父子进程共享这些空间, 当父子进程任意一个进程试图修改某个数据时, 内核会将数据所在
的“页” 整体拷贝一份。




原创粉丝点击