fork()创建子进程步骤、函数用法及常见考点(内附fork()过程图)
2017-06-26 15:43
323 查看
http://blog.csdn.net/yangcs2009/article/details/39267733
#include《unistd.h>
pid_t fork(void);
返回值:子进程中返回0,父进程中返回子进程的ID,出错返回-1
fork函数被调用一次,但返回两次。两次返回的唯一出别是child process的返回值是0,而父进程的返回值则是child process的进程ID。所以可以通过fork函数的返回值来进入父子进程独有的代码段(但是要借助ifelse(else if else )选择语句)。
注:父子进程共享代码段,但是分别拥有自己的数据段和堆栈段。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
int main()
{
fork();
fork();
fork();
printf("hello world\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
char buf[32] = "this is jim";
int main()
{
char buf2[32] = "this is tom";
int pid = fork();
if(pid ==0)
{
printf("this is child ,pid =%d,getppid = %d\n",getpid(),getppid());
strcpy(buf,"jjj");
strcpy(buf2,"ttt");
printf("child:%s\n",buf);
printf("child:%s\n",buf2);
}
else if(pid > 0)
{
sleep(2);
printf("this is parent,childpid=%d,pid=%d\n",getpid(),getppid());
printf("parent:%s\n",buf);
printf("parent:%s\n",buf2);
exit(0);
}
else
{
printf("error\n");
exit(1);
}
printf("hello,pid = %d\n",getpid());
return 0;
}
fork()系统调用函数用法
一个现有进程可以调用fork函数创建一个新的进程。#include《unistd.h>
pid_t fork(void);
返回值:子进程中返回0,父进程中返回子进程的ID,出错返回-1
fork函数被调用一次,但返回两次。两次返回的唯一出别是child process的返回值是0,而父进程的返回值则是child process的进程ID。所以可以通过fork函数的返回值来进入父子进程独有的代码段(但是要借助ifelse(else if else )选择语句)。
注:父子进程共享代码段,但是分别拥有自己的数据段和堆栈段。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
int main()
{
fork();
fork();
fork();
printf("hello world\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
char buf[32] = "this is jim";
int main()
{
char buf2[32] = "this is tom";
int pid = fork();
if(pid ==0)
{
printf("this is child ,pid =%d,getppid = %d\n",getpid(),getppid());
strcpy(buf,"jjj");
strcpy(buf2,"ttt");
printf("child:%s\n",buf);
printf("child:%s\n",buf2);
}
else if(pid > 0)
{
sleep(2);
printf("this is parent,childpid=%d,pid=%d\n",getpid(),getppid());
printf("parent:%s\n",buf);
printf("parent:%s\n",buf2);
exit(0);
}
else
{
printf("error\n");
exit(1);
}
printf("hello,pid = %d\n",getpid());
return 0;
}
相关文章推荐
- fork()创建子进程步骤、函数用法及常见考点(内附fork()过程图)
- fork()创建子进程步骤、函数用法及常见考点(内附fork()过程图)
- fork()创建子进程步骤、函数用法及常见考点(内附fork()过程图)
- 进程的创建过程(fork函数)
- 简单掌握Linux系统中fork()函数创建子进程的用法
- 举例讲解C语言的fork()函数创建子进程的用法
- Linux 内核--fork()函数创建进程
- Linux基础学习系列:对于fork()函数的学习,及进程创建相关知识
- [Chapter 3 Process]Practice 3.1 相关知识:进程创建、fork函数
- Linux 内核--fork()函数创建进程 (续)之copy_mem(int nr, struct task_struct *p)
- Linux下C编程,子进程创建函数fork() 执行解析
- fork(),clone()系统调用进行进程创建的过程
- Linux 内核--fork()函数创建进程
- Linux0.11内核--fork()函数创建进程
- Linux 内核--fork()函数创建进程
- Linux 内核--fork()函数创建进程 (续)之copy_mem(int nr, struct task_struct *p)
- Linux基础学习系列:对于fork()函数的学习,及进程创建相关知识
- Linux0.11内核--fork()函数创建进程
- Linux 内核--fork()函数创建进程 (续)之copy_mem(int nr, struct task_struct *p)
- 如何创建守护进程fork()函数的运用