1.内核分配进程ID是以严格的线性函数方式进行的。如果17是当前id的最高值,那么18就是分配给新进程的值,即使当前新进程运行时,上一个pid为17的进程已经不再运行了。直到内核分配的pid值达到了/proc/sys/kernel/pid_max,内核是不会重用以前分配的值。
2.获得进程ID和父进程ID
getpid():用于返回调用进程的ID
getppid():用于返回调用进程的父进程的ID
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
printf("my pid=%d\n",getpid());
printf("father's pid=%d\n",getppid());
return 0;
}
执行结果:
[root@localhost ~]# ./pid
my pid=9190
father's pid=3299
3.fork():创建一个和当前进程映像一样的进程。
fork之后是父进程先执行还是子进程先执行,这取决于cpu调度算法。
4.linux系统下的多进程遵循POSIX线程接口,称为pthread,在linux多线程需要使用的头文件为<pthread.h>。连接时需要使用库为libthread.
void thread(void)
{
int i;
for(i=0;i<3;i++)
{
printf("This is a pthread.\n");
sleep(1);
}
}
int main(void)
{
pthread_t id;
int i,ret;
ret=pthread_create(&id,NULL,(void*)thread,NULL);
if(ret!=0)
{
printf("Create pthread error!\n");
exit(1);
}
for(i=0;i<3;i++)
{
sleep(1);
printf("This is the main process.\n");
}
pthread_join(id,NULL);
return 0;
}
编译源文件:
[root@localhost thread]# gcc pthread_test.c -o pthread_test -lpthread
[root@localhost thread]#
执行结果:
[root@localhost thread]# ./pthread_test
This is a pthread.
This is a pthread.
This is a pthread.
This is the main process.
This is the main process.
This is the main process.
[root@localhost thread]#