进程

2020-11-30  本文已影响0人  StevenHD
内存空间

text段——可执行的,只读的,不能写
data段——已初始化的数据,可读可写,但是不能执行
bss段——未初始化的数据,可读可写,但是不能执行
Heap, Stack, cmd——均是可读可写

extern可以用来声明这个变量是一个外部变量

在Linux中,所有的进程都是复制出来的,从init进程复制出来的,init进程的PID是1号


孤儿进程会托管给init进程(1号进程)

0号进程是系统创建的第一个进程,也是唯一一个没有通过fork或者kernel_thread产生的进程。完成加载系统后,演变为进程调度、交换


回收子进程,可以用wait()waitpid(),第一个wait()是阻塞的回收,第二个waitpid()是非阻塞轮询回收。

通过kill杀死进程是通过信号来杀死的,也可以等待进程执行结束退出。这是2种,也是运行态和僵尸态的转换。


挂起一个命令可以使用SIGSTOP,也就是kill 19来完成。

父进程产生子进程后,可以通过kill 19让子进程挂起,然后可以再用kill 18让子进程继续运行,然后子进程会正常退出,父进程也会回收子进程。


//
// Created by hlhd on 2020/11/30.
//

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <cstdlib>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

int main1(int argc, char** argv)
{
    int i = 0;
    printf("Current process [%d]\n", getpid());

    pid_t pid = fork();
    if (pid > 0)
    {
        for (i = 0; i < 10; i ++ )
        {
            printf("parent process [%d]\n", getpid());
            sleep(1);
        }
        exit(0);
    }
    else if (pid == 0)
    {
        for (i = 0; i < 5; i ++ )
        {
            printf("child process [%d]\n", getpid());
            sleep(1);
        }
        exit(0);
    }

    return 0;
}

int main2(int argc, char** argv)
{
    printf("Current process's PID = [%d]\n", getpid());
    printf("Current process's PPID = [%d]\n", getppid());

    printf("Current process's UID = [%d]\n", getuid());
    printf("Current process's EUID = [%d]\n", geteuid());

    printf("Current process's GID = [%d]\n", getgid());
    printf("Current process's EGID = [%d]\n", getegid());

    return 0;
}

int main3(int argc, char** argv)
{
    int i = 0;
    pid_t pid = fork();

    if (pid > 0)
    {
        pid_t cpid = wait(nullptr);
        printf("wait child process [%d]\n", cpid);
        exit(0);
    }
    else if (pid == 0)
    {
        for (i = 0; i < 5; i ++ )
        {
            printf("child process [%d]\n", getpid());
            sleep(1);
        }
        exit(0);
    }
    else perror("fork error");

    return 0;
}

int main(int argc, char** argv)
{
    int i = 0;
    pid_t pid = fork();

    if (pid > 0)
    {
        int status;
        pid_t cpid = wait(&status);
        printf("wait child process [%d]\n", cpid);

        if (WIFEXITED(status))
            printf("process [%d] exit %d\n", cpid, WEXITSTATUS(status));
        else if (WIFSIGNALED(status))
            printf("process [%d] signal %d killed\n", cpid, WTERMSIG(status));

        exit(0);
    }
    else if (pid == 0)
    {
        for (i = 0; i < 5; i ++ )
        {
            printf("child process [%d]\n", getpid());
            sleep(1);
        }
        exit(1);
    }
    else perror("fork error");

    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读