scheduler02
fork()、vfork()、pthread_create()
$ cat test.c
#include <sched.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int data = 10;
int child_process()
{
printf("Child process %d, data %d\n",getpid(),data);
data = 20;
printf("Child process %d, data %d\n",getpid(),data);
_exit(0);
}
int main(int argc, char* argv[])
{
int pid;
// pid = fork();
// pid = vfork();
if(pid==0) {
child_process();
}
else{
sleep(1);
printf("Parent process %d, data %d\n",getpid(), data);
exit(0);
}
}
$ gcc test.c -o test
# 当pid = fork();时
$ ./test
Child process 2646, data 10
Child process 2646, data 20
Parent process 2645, data 10
$ strace ./test
...
clone(child_stack=x, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=xxx)
...
# 当pid = vfork();时
$ ./test
Child process 2702, data 10
Child process 2702, data 20
Parent process 2701, data 20
$ strace ./test
xxxxx
$ cat thread.c
#include <stdio.h>
#include <pthread.h>
#include <stdio.h>
#include <linux/unistd.h>
#include <sys/syscall.h>
int data = 10;
static pid_t gettid( void )
{
return syscall(__NR_gettid);
}
static void *thread_fun(void *param)
{
data = 20;
printf("thread pid:%d, tid:%d pthread_self:%lu\n", getpid(), gettid(),pthread_self());
printf("data %d\n", data);
return NULL;
}
int main(void)
{
pthread_t tid;
int ret;
printf("thread pid:%d, tid:%d pthread_self:%lu\n", getpid(), gettid(),pthread_self());
printf("data %d\n", data);
ret = pthread_create(&tid, NULL, thread_fun, NULL);
if (ret == -1) {
perror("cannot create new thread");
return -1;
}
if (pthread_join(tid, NULL) != 0) {
perror("call pthread_join function fail");
return -1;
}
printf("thread pid:%d, tid:%d pthread_self:%lu\n", getpid(), gettid(),pthread_self());
printf("data %d\n", data);
return 0;
}
$ gcc thread.c -pthread -o thread
$ ./thread
thread pid:1878, tid:1878 pthread_self:140648953210624
data 10
thread pid:1878, tid:1879 pthread_self:140648945157904
data 20
thread pid:1878, tid:1878 pthread_self:140648953210624
data 20
$ strace ./thread
...
clone(child_stack=xxx,flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=xxx,tls=xxx, child_tidptr=xxx) = xxx
...为什么 线程称为轻量级进程?
进程1和进程0
孤儿进程
进程睡眠
Last updated