IO进程(学习)2024.8.19

embedded/2024/9/23 0:35:49/

目录

进程

函数

创建进程

定义

案例

特点

进程回收

定义

案例

进程退出

定义

 案例

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;
}

http://www.ppmy.cn/embedded/97866.html

相关文章

centos7突然掉电后启动报错/dev/mapper/centos-root does not exist

问题现象 物理服务器SR588已安装centos7&#xff0c;突然掉电后系统进不去&#xff0c;提示/dev/mapper/centos-root does not exist 问题解决过程 网上搜索相关的解决方法 1、 用此方法不行 2、 用此方法也是不行 3、 分析查看ls /dev/mapper&#xff0c;目录底下没有cent…

FPGA 最小系统 EP2C5T144C8N

参考 &#xff1a; 微雪 ep2c5t 米尔 所需元件&#xff1a; 1.2v 3.3v稳压芯片 7个10k电阻 一个use blast 5v-》3.3v稳压-》1.2v稳压 1.JTAG连接 JTAG连接 NSTATUS nconfig config_done 因为没有外部存储器&#xff0c;直接使用Jtag烧录&#xff0c;从而nconfig 为3.3 &…

如何设计一个分布式任务调度器

设计一个分布式任务调度器是一个复杂但非常有价值的项目&#xff0c;它可以用来处理大量的任务并在多个节点之间分配执行。下面是一个关于如何设计这样一个系统的概述&#xff0c;包括关键技术点和实现细节。 需求分析 首先明确分布式任务调度器的目标和需求&#xff1a; • 任…

深入学习SQL优化的第二天

目录 连接 聚合函数 SQL 优化&#xff0c;直接练习写SQL语句&#xff0c;并不仅仅是为了学习 SQL 本身&#xff0c;它实际上也是学习 SQL 优化的一种非常有效的方式&#xff0c;通过不断地编写、执行和调整SQL查询&#xff0c;你可以深入理解数据库的工作原理、查询的执行计划…

【C语言】进程和线程详解

目录 C语言进程和线程详解1. 进程和线程的对比2. 进程的基本概念2.1 进程的定义2.2 进程的特点2.3 进程的生命周期 3. 进程管理3.1 进程创建3.2 进程间通信&#xff08;IPC&#xff09;3.2.1 管道&#xff08;Pipe&#xff09; 4. 线程的基本概念4.1 线程的定义4.2 线程的特点 …

pytest.ini介绍

1.pytest.ini是什么 &#xff1f; pytest.ini文件是pytest的主配置文件&#xff1b;pytest.ini文件的位置一般放在项目的根目录下&#xff0c;不能随便放&#xff0c;也不能更改名字。在pytest.ini文件中都是存放的一些配置选项 &#xff0c;这些选项都可以通过pytest -h查看到…

糖尿病如何预防?

预防糖尿病的方法&#xff1a;   1、健康饮食&#xff1a;均衡的饮食对于预防糖尿病至关重要。建议增加全谷物、蔬菜、水果的摄入&#xff0c;限制高糖、高脂肪和高热量食物的摄入。同时&#xff0c;减少加工食品和含糖饮料的摄入&#xff0c;以降低血糖水平和体重。   2、…

使用 Tailwind CSS 实现水平和垂直居中对齐的方法

在前端开发中&#xff0c;可以使用 Tailwind CSS 轻松实现水平和垂直居中对齐。 方法 1&#xff1a;使用 flex 布局 这种方法最常用且灵活&#xff0c;可以适应各种情况。 <div class"flex items-center justify-center h-screen"><div><!-- 这里是…