封装fork/wait等操作编写一个process_create函数

利用回调函数封装fork wait execvp 等函数, 编写一个process_create函数

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

int process_create(int(*func)(), const char *file, char *argv[])
{
    int ret = 0;
    pid_t pid = fork();
    if(pid == 0)
    {
        //子进程
        ret = func(file, argv);
        if(ret == -1)
        {
            printf("调用execvp失败\n");
            perror("func");
            _exit(-1);
        }

    }
    else
    {
        int st;
        pid_t ret = wait(&st);
        if(ret == -1)
        {
            perror("wait");
            exit(-1);
        }
    }
    return 0;
}

int main()
{
    char *argv1[] = {"ls"};
    char *argv2[] = {"ls", "-al", "/etc/passwd", 0};
    process_create(execvp, *argv1, argv2);
    return 0;
}

这里写图片描述

猜你喜欢

转载自blog.csdn.net/yu876876/article/details/80323438