linux 進程 fork wait函數
fork:創建子進程
wait:父進程等待子進程結束,並銷燬子進程,如果父進程不調用wait函數,子進程就會一直留在linux內核中,變成了殭屍進程。
fork函數的詳細說明:fork
wait函數詳細說明參考:wait
例子1:不註釋掉exit(0)的話,子進程不會執行到printf("end pid: %d\n", getpid());這行。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <wait.h>//wait function
int main(){
pid_t pid;
pid = fork();
if(pid == 0){
printf("child process : %d\n", getpid());
//exit(0);
}
else{
int status;
pid_t waitpid;
printf("parent process : childpid=%d , mypid=%d\n",pid, getpid());
waitpid = wait(&status);
printf("waitpid:%d\n", waitpid);
}
printf("end pid: %d\n", getpid());
return 0;
}
例子2:父進程和子進程之間,值是不共有的,你是你的,我是我的。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(){
pid_t pid;
int i = 100;
pid = fork();
if(pid == 0){
printf("child process : %d\n", getpid());
i += 500;
}
else{
printf("parent process : childpid=%d , mypid=%d\n",pid, getpid());
i += 1024;
}
printf("i=%d\n", i);
return 0;
}
例子3:線程之間,值是共有的。
#include <stdio.h>
#include <unistd.h>//sleep function
#include <pthread.h>
int global_val = 0;
void* sub_thread(void *data){
int* val = (int*)data;
printf("sub_thread : val=%d\n", *val);
for(int i = 0; i < 10; ++i){
global_val++;
printf("sub_thread : i=%d, g=%d\n", i, global_val);
sleep(1);
}
return NULL;
}
int main(){
pthread_t th;
void* th_ret;
int arg = 200;
if(pthread_create(&th, NULL, sub_thread, (void*)&arg) != 0){
perror("pthread_create");
return 1;
}
for(int i = 0; i < 10; ++i){
global_val++;
printf("main: i=%d, g=%d\n", i, global_val);
sleep(1);
}
if(pthread_join(th, &th_ret) != 0){
perror("pthread_join");
return 1;
}
return 0;
}
編譯時需要加 -pthread
g++ -g process-5-thread.cpp -std=c++11 -pthread