2.1 Linux进程介绍

进程:

       1. 进程就是处于执行器的程序。通常是调用fork系统,系统通过复制现有进程来创建新的进程。

        2.每个进程都有一个task_struct数据结构,称为进程描述符和一片用作系统空间堆栈的存储空间。



     3. 内核通过标识进程pid来识别进程 ,也就是pid_t 它的类型是int。

     4. 

         进程执行的第一步:通过fork()创建一个进程。

         fork 是如何运行的呢,参见  http://www.codeceo.com/article/linux-kernel-create-process.html

#include <stdio.h>
#include <unistd.h>

int main(int argc, const char * argv[]) {
  // insert code here...
  pid_t pid;
  if((pid = fork()) == 0){
    //返回0的是子进程
    printf("child pid: %d\n", getpid());
  } else {
    printf("pid: %d\n", pid);//父进程中返回子进程的pid
    printf("father pid: %d\n", getpid());
  }
}

    5. 生命周期

    进程执行的第二部:调用execve()

     创建进程的目的一般是为了执行新的目标程序, Linux提供了一个系统调用execve(), 让一个进程执行以文件形式存在的可执行程序的映像。

1 #include <stdio.h> 
2.int main()
4 {
5 int child;
6 char *args[] = { "/bin/echo", "Hello", "World!", NULL};
7 8
if (!(child = fork())) //创建一个子进程
9 {
10 /* child */
11 printf("pid %d: %d is my father\n", getpid(), getppid());
12 execve("/bin/echo", args, NULL);
13 printf("pid %d: I am back, something is wrong!\n", getpid());
14 }
15 else
16 {
17 int myself = getpid();   //子进程的pid
18 printf("pid %d: %d is my son\n", myself, child);
19 wait4(child, NULL, 0, NULL); //父进程停止运行
20 printf("pid %d: done\n", myself);
21 }
22 return 0;
23  }










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值