IO进程(学习)2024.8.19

目录

进程

函数

创建进程

定义

案例

特点

进程回收

定义

案例

进程退出

定义

 案例

exit和return区别

获取进程号

定义

案例

fork函数补充

1.读时共享写时拷贝

2.vfork和fork的区别

exec函数族

案例

守护进程

特点

步骤

案例:守护进程循环1s向文件中写入字符“hello”

线程

概念

进程和线程的区别

函数

创建线程

定义

案例

线程回收

定义

案例

线程退出

定义

案例

获取线程ID

定义

案例

线程分离函数

定义

案例

使用方式

注意事项

取消线程

定义

案例

进程

函数

创建进程

定义

#include <sys/types.h>
#include <unistd.h>
pid_t fork(void);        (原有的进程是父进程,新创建的进程是子进程)
功能:创建子进程
返回值:
        成功:在父进程中:返回子进程的进程号 >0
                   在子进程中:返回值为0
        失败:-1并设置errno

案例
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char const *argv[])
{
    pid_t pid;

    pid = fork();
    if (pid < 0)
    {
        perror("fork函数出错");
        return -1;
    }
    // 子进程
    else if (pid == 0)
    {
        printf("in the 子进程\n");
    }
    // 父进程
    else
    {
        printf("in the 父进程\n");
    }
    return 0;
}
特点

1.子进程几乎拷贝了父进程的全部内容。包括代码、数据、系统数据段中的pc值、栈中的数    据、父进程中打开的文件等;但它们的PID、PPID是不同的。
2.父子进程有独立的地址空间,互不影响;当在相应的进程中改变全局变量、静态变量,都互不影响。
3.若父进程先结束,子进程成为孤儿进程,被init进程收养,子进程变成后台进程。
4.若子进程先结束,父进程如果没有及时回收,子进程变成僵尸进程(要避免僵尸进程产生)

进程回收

定义

#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *status);
功能:回收子进程资源,阻塞函数,等待子进程退出后结束阻塞
参数:status:子进程退出状态,不接受子进程状态设为NULL
返回值:成功:回收的子进程的进程号
              失败:-1

pid_t waitpid(pid_t pid, int *status, int options);
功能:回收子进程资源
参数:
        pid:>0     指定子进程进程号
                =-1   任意子进程  (等待任意子进程)
                =0    等待其组ID等于调用进程的组ID的任一子进程 
                <-1   等待其组ID等于pid的绝对值的任一子进程
        status:子进程退出状态
        options:0:阻塞
                        WNOHANG:非阻塞  (没有子进程退出会立刻返回)
返回值:正确:返回结束的子进程的进程号
              当使用选项WNOHANG且没有子进程结束时:0
              失败:-1

案例
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <wait.h>

int main(int argc, char const *argv[])
{
    pid_t pid;

    pid = fork();
    if (pid < 0)
    {
        perror("fork函数出错");
        return -1;
    }
    // 子进程
    else if (pid == 0)
    {
        printf("in the子进程\n");
    }
    // 父进程
    else
    {
        wait(NULL);
        printf("in the 父进程\n");
        while(1)
    }
    return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <wait.h>

int main(int argc, char const *argv[])
{
    pid_t pid;

    pid = fork();
    if (pid < 0)
    {
        perror("fork函数出错");
        return -1;
    }
    // 子进程
    else if (pid == 0)
    {
        printf("进入子进程\n");
        sleep(5);
        printf("子进程结束\n");
    }
    // 父进程
    else
    {
        printf("进入父进程\n");
        while (1)
        {
            int ret = waitpid(pid, NULL, WNOHANG);
            if (ret == 0)
            {
                sleep(1);
                printf("父进程等待\n");
            }
            if (ret == pid)
            {
                printf("捕获子进程结束\n");
                break;
            }
        }
    }
    return 0;
}

补充:        wait(NULL);         等价于waitpid(-1, NULL, 0);

进程退出

定义

void exit(int status);
功能:结束进程,刷新缓存

void _exit(int status);
功能:结束进程,不刷新缓存
参数:status是一个整型的参数,可以利用这个参数传递进程结束时的状态。通常0表示正常结束;其他的数值表示出现了错误,进程非正常结束

 案例
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char const *argv[])
{
    pid_t pid;
    pid = fork();
    if (pid < 0)
    {
        perror("fork函数出错");
        return -1;
    }
    // 子进程
    else if (pid == 0)
    {
        printf("in the 子进程\n");
    }
    // 父进程
    else
    {
        printf("in the 父进程\n");
        //exit(0);    //刷新缓存区
        _exit(0);    //不刷新缓存
        while(1);
    }
    return 0;
}
exit和return区别

        exit:不管在子函数还是主函数,都可以结束进程                                                                    return:当子函数中有return时返回到函数调用位置,并不结束进程

获取进程号

定义

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

pid_t getpid(void);
功能:获取当前进程的进程号


pid_t getppid(void);
功能:获取当前进程的父进程号

案例

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

int main(int argc, char const *argv[])
{
    pid_t pid;
    pid = fork();
    if (pid < 0)
    {
        perror("fork函数出错");
        return -1;
    }
    // 子进程
    else if (pid == 0)
    {
        printf("in the 子进程 进程号%d 父进程号%d\n", getpid(), getppid());
    }
    // 父进程
    else
    {
        printf("in the 父进程 进程号%d 父进程号%d 子进程号为%d\n", getpid(), getppid(), pid);
    }
    return 0;
}

fork函数补充

1.读时共享写时拷贝

读时共享:刚fork出来之后,两个地址空间用户区数据完全相同,父子进程都指向同一块共享区域,父子进程中都映射到共享区域中的变量(int num)

写时拷贝:当后续父子进程对共享区域中的变量进行不同的操作时(父进程对num++,子进程对num--),发生写时拷贝原则,父子进程各自拷贝出来独立的空间存放自己的num,因此父子进程中空间是相互独立,互不影响的,因此父子进程之间不能够使用全局变量进行通信。

2.vfork和fork的区别

共同点:创建子进程
执行顺序:vfork先执行子进程,子进程调用exit函数结束进程时,父进程再执行
                  fork父子进程执行顺序没有先后
地址空间:fork创建的子进程复制父进程的全部内容,有独立的地址空间
                  vfork创建的子进程和父进程共享地址空间

exec函数族

功能:在一个进程中执行另一个程序
int execl(const char *path, const char *arg, ...,NULL);
参数:path:执行的程序的路径
           arg:程序名称
           ...:参数列表
           NULL:结束标志

案例
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    printf("hello\n");
    // execl("/bin/ls", "ls", "-l", NULL);
    system("ls");
    return 0;
}

守护进程

特点

1.守护进程的生命周期较长,在系统启动时开启,系统关闭退出

2.守护进程是一个后台进程不依赖于控制终端,且周期性执行的一个进程

步骤

1.创建子进程,父进程退出
        让子进程变成孤儿进程,成为后台进程;        fork()
2.在子进程中创建新会话
        让子进程成为会话组组长,为了让子进程完全脱离终端;        setsid()
3.修改进程运行路径为根目录
        原因进程运行的路径不能被卸载;        chdir("/")
4.重设文件权限掩码
        目的:增大进程创建文件时权限,提高灵活性;        umask(0)
5.关闭文件描述符 (守护进程是一个后台进程,不需要和用户进行交互)
        将不需要的文件关闭;        close()

案例:守护进程循环1s向文件中写入字符“hello”

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>

int main(int argc, char const *argv[])
{
    pid_t pid;

    pid = fork();
    int fd = open(argv[1], O_RDWR);
    if (pid < 0)
    {
        perror("fork函数出错");
        return -1;
    }
    // 子进程
    else if (pid == 0)
    {
        // 在进程中创建新会话
        setsid();

        // 改变当前目录为根目录
        chdir("/");

        // 重设文件权限源码
        umask(0);

        // 关闭文件描述符
        close(0);

        while (1)
        {
            write(fd, "hello\n", 6);
            sleep(1);
        }
    }
    // 父进程
    else
    {
        exit(0);
    }
    return 0;
}

线程

概念

轻量级的进程
同一个进程中创建多个线程共享进程地址空间,引入线程可以提高系统的性能

进程和线程的区别

共同点:都为系统提供并发的执行的能力
不同点:
资源和调度:进程是系统资源分配的最小单位

                   线程是资源调度的最小单位
地址空间:每个进程都有独立的地址空间;

                同一个进程中的多个线程共享进程地址空间
通信方面:多线程的通信比较简单,借助全局变量,但是需要考虑临界资源的访问问题;

                多进程的通信比较复杂,需要借助3-4g的内核空间(共享的)来完成通信
安全性方面:进程相对比较安全(空间独立,一个进程退出不会影响其他进程),
                   线程安全性相对较低,进程退出其中的线程会随之结束

函数

创建线程

定义

#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
功能:创建线程
参数:thread:线程标识 (线程ID)
           attr:线程属性, NULL:代表设置默认属性
           start_routine:函数名:代表线程函数
           arg:用来给前面函数传参
返回值:成功:0
              失败:错误码

案例
#include <stdio.h>
#include <pthread.h>

// 子线程
void *handler(void *arg)
{
    printf("in the 子线程\n");
    return NULL;
}

int main(int argc, char const *argv[])
{
    pthread_t tid;
    if (pthread_create(&tid, NULL, handler, NULL) !=0)
    {
        perror("pthread_create函数失败");
        return -1;
    }

    //主线程
    printf("in the 主线程\n");
    while(1);

    return 0;
}

补充:编译程序时要手动链接线程库        gcc xxx.c -lpthread

线程回收

定义

int  pthread_join(pthread_t thread,  void **value_ptr) 
功能:用于等待一个指定的线程结束,阻塞函数
参数:thread:创建的线程对象
           value_ptr:指针*value_ptr指向线程返回的参数
返回值:成功:0
            失败:errno

案例
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

// 子线程
void *handler(void *arg)
{
    sleep(3);
    printf("in the 子线程\n");
    return NULL;
}

int main(int argc, char const *argv[])
{
    pthread_t tid;
    if (pthread_create(&tid, NULL, handler, NULL) != 0)
    {
        perror("pthread_create函数失败");
        return -1;
    }

    // 主线程
    printf("in the 主线程\n");

    // 阻塞等待线程退出,回收线程资源
    pthread_join(tid, NULL);

    return 0;
}

线程退出

定义

void  pthread_exit(void *value_ptr) 
功能:用于退出线程的执行
参数:value_ptr:线程退出时返回的值  (相当于给他传递的状态值)
返回值:无

案例
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

// 子线程
void *handler(void *arg)
{
    sleep(3);
    printf("in the 子线程\n");
    pthread_exit(NULL);
    printf("exit\n");
    return NULL;
}

int main(int argc, char const *argv[])
{
    pthread_t tid;
    if (pthread_create(&tid, NULL, handler, NULL) != 0)
    {
        perror("pthread_create函数失败");
        return -1;
    }

    // 主线程
    printf("in the 主线程\n");

    // 阻塞等待线程退出,回收线程资源
    pthread_join(tid, NULL);

    return 0;
}

获取线程ID

定义

pthread_t  pthread_self(void);
功能:获取线程号
返回值:线程ID

案例
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

// 子线程
void *handler(void *arg)
{
    sleep(3);
    printf("in the 子线程 线程号%lu\n", pthread_self());
    pthread_exit(NULL);
    printf("exit\n");
    return NULL;
}

int main(int argc, char const *argv[])
{
    pthread_t tid;
    if (pthread_create(&tid, NULL, handler, NULL) != 0)
    {
        perror("pthread_create函数失败");
        return -1;
    }

    // 主线程
    printf("in the 主线程 线程号%lu 子线程号%lu\n", pthread_self(), tid);

    // 阻塞等待线程退出,回收线程资源
    pthread_join(tid, NULL);

    return 0;
}

线程分离函数

定义

        设置线程分离属性,保证子线程在退出时,系统可以自动完成资源回收,不需要调用 pthread_join函数进行回收

int pthread_detach(pthread_t thread);
功能:让线程分离,线程退出让系统自动回收线程资源
参数:线程ID

          子线程在退出的时候,主线程没有给子线程回收资源的话,线程会变成僵尸线程

案例
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

// 子线程
void *handler(void *arg)
{
    sleep(3);
    printf("in the 子线程 线程号%lu\n", pthread_self());
    pthread_exit(NULL);
    printf("exit\n");
    return NULL;
}

int main(int argc, char const *argv[])
{
    pthread_t tid;
    if (pthread_create(&tid, NULL, handler, NULL) != 0)
    {
        perror("pthread_create函数失败");
        return -1;
    }

    // 主线程
    printf("in the 主线程 线程号%lu 子线程号%lu\n", pthread_self(), tid);

    pthread_detach(tid);

    return 0;
}
使用方式

1.在主线程中调用pthread_detach(tid);
2.在子线程中调用pthread_detach(pthread_self());

注意事项

1.如果线程已经设置了分离状态,则再调用pthread_join就会失败
2.当主线程中希望有阻塞操作时,可以选择调用pthread_join函数回收线程
   当主线程本身有循环操作,希望子线程在结束时立马回收线程,可以选择pthread_detach设置分离属性
3.设置线程的分离属性有两种方式        
        (1)通过pthread_detach进行设置
        (2)通过pthread_create函数的第二个参数(线程属性)来设置分离属性

取消线程

定义

#include <pthread.h>
int pthread_cancel(pthread_t thread);
功能:向一个指定的线程发送取消请求
参数:thread:线程ID
返回值:成功:0

              失败:错误码

pthread_testcancel()
功能:检查取消请求

案例
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

// 子线程
void *handler(void *arg)
{
    sleep(3);
    printf("in the 子线程 线程号%lu\n", pthread_self());
    while (1)
    {
        pthread_testcancel();
    }
    printf("exit\n");
    return NULL;
}

int main(int argc, char const *argv[])
{
    pthread_t tid;
    if (pthread_create(&tid, NULL, handler, NULL) != 0)
    {
        perror("pthread_create函数失败");
        return -1;
    }

    // 主线程
    printf("in the 主线程 线程号%lu 子线程号%lu\n", pthread_self(), tid);
    sleep(1);
    pthread_cancel(tid);

    pthread_join(tid, NULL);
    return 0;
}

综合练习题:主线程循环从终端输入字符串,子线程循环将字符串打印至终端,当输入"quit"时结束

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>

char a[100];
int flag = 0; // 0表示无新数据,1表示有新数据

void *handler(void *arg)
{
    while (1)
    {
        sleep(1);
        if (strcmp(a, "quit") == 0)
        {
            break;
        }
        if (flag == 1)
        {
            printf("%s\n", a);
            flag = 0;
        }
    }
    return NULL;
}

int main()
{
    pthread_t tid;
    if (pthread_create(&tid, NULL, handler, NULL) != 0)
    {
        perror("pthread_create函数失败");
        return -1;
    }
    while (1)
    {
        scanf("%s", a);
        getchar();
        flag = 1;
        if (strcmp(a, "quit") == 0)
        {
            flag = 0;
            break;
        }
    }

    pthread_join(tid, NULL);
    return 0;
}
  • 17
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值