Linux进程、线程中的常用函数

来源:互联网 发布:c语言游戏编程入门 编辑:程序博客网 时间:2024/06/05 12:04

自己复习用,已经比较熟的就不多写了。

1、进程相关的函数

(1)getpid


(2)getppid


(3)进程创建:fork

注意:子进程fork之后获得了父进程的数据空间、堆栈的复制品。


(4)sleep


(5)exec函数族

这个比较复杂,有:execl、execv、execle、execve、execlp、execvp六个函数。

l的意思是函数接收以逗号分隔的参数列表,最后以NULL为结束标志,例如:execl("/bin/ls","ls","-l",NULL);

v的意思是函数接收以NULL结尾的字符串数组的指针,例如我们先准备好指针:char* arg[]={"ls","-l","NULL"},就可以用execv("/bin/ls",arg)来调用执行ls -l命令了。

p的意思是函数接收以NULL结尾的字符串数组指针,函数可以PATH变量去查找子程序文件(也就是说我们不用自己去指定路径了),例如execlp("ls","ls","-l",NULL);

e的意思是说我们可以改变子进程的环境,如果没有e,默认使用当前的环境。


(6)_exit

 终止进程,缓冲区将不被保存。


(7)exit

 终止进程,缓冲区被保存。

 

(8)wait

传入一个整型指针来获取子进程结束的状态,一般要配合其他宏使用。执行结束后返回子进程的id号。

 

(9)waitpid

waitpid(pid_tpid, int* status, int options),第一个参数是子进程id,第二个是子进程状态,

 

2、线程相关的函数

(1)pthread_create

这个函数比较复杂:int pthread_create(pthread_t * thread, const pthread_attr_t * attr,void * (* start_routine)(void*), void* arg)。

第一个参数接收一个pthread_t类型的指针,第二个参数是属性,通常设为NULL,第三个参数是一个名为start_routine的函数指针,用来传递要在线程中执行的代码,最后一个是传给这个线程的参数。

 示例代码:

#include<stdio.h>#include<string.h>#include<stdlib.h>#include<pthread.h>#include<unistd.h>pthread_t ntid;void printids(const char* s){pid_t pid;pthread_t tid;pid=getpid();tid=pthread_self();printf("%s pid = %u tid = %u (0x%x)\n",s,\(unsigned int)pid,(unsigned int)tid,(unsigned int)tid);}void *thread_fun(void* arg){printids(arg);return NULL;}int main(void){int err;err=pthread_create(&ntid,NULL,thread_fun,"我是新线程");if(err!=0){fprintf(stderr,"创建线程失败:%s\n",strerror(err));exit(1);}printids("我是父进程:");sleep(2);return 0;}

(2)pthread_exit

传入一个无类型指针终止线程。

 

(3)pthread_join

类似waitpid,传入要等待的线程的线程号,第二个参数用来接收线程返回值,通常可设为NULL,这个函数会把当前线程挂起,等待指定的线程结束。


原创粉丝点击