pthread_create() 和 fork() 区别
pthread_create()
// pthread
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
void* child(void *arg){
printf("child...\n");
pid_t pid=getpid();
printf("child: pid = %d\n", pid);
sleep(1000);
}
void parent(){
printf("parent...\n");
pid_t pid=getpid();
printf("parent: pid = %d\n", pid);
sleep(1000);
}
void error(){
perror("fork:");
exit( -1);
}
int main(){
pthread_t id;
pthread_create(&id,NULL, child,NULL);
printf("new thread id %lu\n",id);
parent();
return 0;
}
输出:
new thread id 139976466216704
parent...
parent: pid = 3408
child...
child: pid = 3408
$ ps -ef|grep test4
ubuntu 3408 1244 0 09:27 pts/1 00:00:00 ./test4
ubuntu 3415 1761 0 09:27 pts/10 00:00:00 grep --color=auto test4
fork()
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
void child(){
printf("child...\n");
pid_t pid=getpid();
printf("child: pid = %d\n", pid);
sleep(1000);
}
void parent(){
printf("parent...\n");
pid_t pid=getpid();
printf("parent: pid = %d\n", pid);
sleep(1000);
}
void error(){
perror("fork:");
exit( -1);
}
int main(){
int pid;
pid=fork();
if(pid==0){
child();
}else if(pid>0){
printf("child process id %d\n",pid);
parent();
}else{
error();
}
return 0;
}
new process id 3318
parent...
parent: pid = 3317
child...
child: pid = 3318
$ ps -ef|grep test3
ubuntu 3317 1244 0 09:26 pts/1 00:00:00 ./test3
ubuntu 3318 3317 0 09:26 pts/1 00:00:00 ./test3
ubuntu 3351 1761 0 09:26 pts/10 00:00:00 grep --color=auto test3
所以如果不去深究内部的实现机制,那么从外面看,thread 和 process 还是可以套用经典的操作系统的概念的。
另外一点,pthread 的代码编译时要加上-lpthread
,而 fork 则不用去额外链接库。