#include <unistd.h>
#include<stdio.h>
#include <sys/types.h>
int main()
{
pid_t pid;
// pid_t fork();
pid = getpid();
printf("my pid is : %d\n",pid);
while(1);
return 0;
}
~
~
获取进程id
#include <unistd.h>
#include<stdio.h>
#include <sys/types.h>
int main()
{
pid_t pid;
pid_t pid2;
// pid_t fork();
pid = getpid();
printf("before fork pid is %d\n", pid);
fork();
pid2 = getpid();
printf("after fork pid is %d\n", pid2);
if(pid==pid2){
printf("it is father print, current pid is %d\n",getpid());
}
else{
printf("it is child print, current pid is %d \n",getpid());
}
return 0;
}
~
~
~
~
~
~
~
~
fork的一些基本用法
#include <unistd.h>
#include<stdio.h>
#include <sys/types.h>
#include <stdlib.h>
int main()
{
pid_t pid;
// pid_t fork();
int cnt = 0;
pid = vfork();
if(pid > 0){
while(1){
printf("cnt = %d \n",cnt);
printf("this is father print , pid =%d\n",getpid());
sleep(1);
}
}
else if(pid == 0){
while(1){
printf("it is child print, current pid is %d \n",getpid());
sleep(1);
cnt++;
if(cnt == 5){
exit(0);
}
}
}
return 0;
}
~
~
vfork 的一些使用`
#include <unistd.h>
#include<stdio.h>
#include <sys/types.h>
#include <stdlib.h>
int main()
{
pid_t pid;
// pid_t fork();
int cnt = 0;
int status = 10;
pid = fork();
if(pid > 0){
wait(&status);
printf("child quit , child status is %d",WEXITSTATUS(status));
while(1){
printf("cnt = %d \n",cnt);
printf("this is father print , pid =%d\n",getpid());
sleep(1);
}
}
else if(pid == 0){
while(1){
printf("it is child print, current pid is %d \n",getpid());
sleep(1);
cnt++;
if(cnt == 5){
exit(0);
}
}
}
return 0;
}
~
~
引入wait 使用