创建进程的两种方式

fork:
#include <sys/types.h>
#include <unistd.h>

#include <sys/stat.h>
#include <fcntl.h>

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

#include <signal.h>
#include <errno.h>
#include <signal.h>

int main(void )
{
    int fd;
    pid_t pid;
    signal(SIGCHLD, SIG_IGN);
    printf("befor fork pid:%d \n", getpid());

int num = 10; //思考打印
    fd = open("11.txt", O_WRONLY);
    if (fd == -1)
    {
        return 0;
    }

    pid = fork();
    if (pid == -1)  
    {
        printf("pid < 0 err.\n");
        return -1;
    }
    if (pid > 0)
    {
        printf("parent: pid:%d \n", getpid());
        write(fd, "parent", 6);
        close(fd);

        //sleep(1);
    }
    else if (pid == 0)
    {
        printf("child: %d, parent: %d \n", getpid(), getppid());
        write(fd, "child", 5);
        close(fd);
        //sleep(100);
    }

    printf("fork after....\n");
    return 0;
}

vfork:
#include <sys/types.h>
#include <unistd.h>

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

#include <signal.h>
#include <errno.h>
#include <signal.h>


int main01(void )
{
    pid_t pid;
    int ret = 0;

    printf("befor fork pid:%d \n", getpid());
    int abc = 10;
    pid = vfork(); //errno
    if (pid == -1)  
    {
        //printf("pid < 0 err.\n");
        perror("tile");
        return -1;
    }
    if (pid > 0)
    {

        printf("parent: pid:%d \n", getpid());


    }
    else if (pid == 0)
    {
        printf("child: %d, parent: %d \n", getpid(), getppid());
        //printf("abc:%d\n", abc);

        ret =  execve("./hello", NULL, NULL);
        if (ret == -1)
        {
            perror("execve:");
        }
        printf("execve 测试有没有执行\n");

            exit(0);
        }

    printf("fork after....\n");
    return 0;
}


int main(void )
{
    pid_t pid;
    int ret = 0;

    printf("befor fork pid:%d \n", getpid());
    int abc = 10;
    pid = vfork(); //errno
    if (pid == -1)  
    {
        //printf("pid < 0 err.\n");
        perror("tile");
        return -1;
    }
    if (pid > 0)
    {
        printf("parent: pid:%d \n", getpid());

    }
    else if (pid == 0)
    {
        printf("child: %d, parent: %d \n", getpid(), getppid());
        //printf("abc:%d\n", abc);
        char *const argv[] = {"ls", "-l", NULL};
        ret =  execve("/bin/ls", argv, NULL);
        if (ret == -1)
        {
            perror("execve:");
        }
        printf("execve 测试有没有执行\n");

            exit(0);
        }

    //printf("fork after....\n");
    return 0;
}









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值