1 进程概念
在自身的虚拟空间中运行的占据系统资源的程序。
2 父子进程
fork一个进程以后,都将会产生一个子进程,这个子进程拷贝了父进程的资源(可以使用execve来覆盖父进程的运行代码)。
3 僵死进程
当子进程退出,而父进程并没有回收机制(收尸)或者显式的忽略该信号的话,子进程就将变成僵尸进程。
4 例子
1)
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
pid_t chl_pid;
int status;
if((chl_pid = fork()) < 0)
{
printf("fork error\n");
exit(-1);
}
else if(chl_pid >0)
{
/* if parent dones't process the signal or ignore this signal,
* then child will be a zimble signal
* (of course,there will be another method to kill the zimble
* process,which is kill the parent process,then the child
* process will be adoptted to 1st process)
*/
printf("this is parent\nchild pid : %d",chl_pid);
wait(&status);
while(1);
}
else
{
printf("this is child\n");
}
return 0;
}
2)多个子进程
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
int ret;
int wait_ch1_status,wait_ch2_status; //wait for child process's signal
pid_t pid_1,pid_2;
if( (ret =fork()) == 0 )
{
printf("child 1 process\n");
exit(1);
}
else
{
pid_1 = ret;
printf("pid 1 :%d\n",pid_1);
//father
if( (ret = fork()) ==0)
{
printf("child 2 process\n");
exit(1);
}
else
{
pid_2 = ret;
printf("pid 2:%d\n",pid_2);
printf("parent process\n");
waitpid(pid_1,&wait_ch1_status,P_PID);
waitpid(pid_2,&wait_ch2_status,P_PID);
while(1);
}
}
}
3) execve()
/* myecho.c */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("123\n");
exit(0);
}
/* execve.c */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
char *newargv[] = {"hello","world",NULL};
char *env[] = {NULL};
execve(argv[1],newargv,env);
perror("execve");
exit(EXIT_FAILURE);
}
编译后
执行 $ ./execve ./myecho
打印123