利用fork()、wait()等函数模拟实现进程创建函数process_create()函数
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
typedef void *(*FUNC)(void *);
typedef struct Arg{
int reg;
} Arg;
void* func(void *parameter){
(void)parameter;
printf("haha\n");
return NULL;
}
void process_create(pid_t *pid,void *func,void *arg){
int id = fork();
if(id < 0){
perror("fork:");
return ;
}else if(id == 0){
//child
FUNC funcback = (FUNC)func;
funcback((Arg *)arg);
exit(0);
}else{
//father
*pid = wait(NULL);
}
}
int main(){
pid_t pid;
Arg arg;
process_create(&pid,func,&arg);
printf("pid = %d\n",pid);
return 0;
}
结果:
[DELL@localhost lesson6]$ ./process_create
haha
pid = 6852
[DELL@localhost lesson6]$