fork

先看一个例子:

#include <iostream>
#include <cstdlib>
#include <unistd.h>
using namespace std;

int main()
{
    pid_t pid = 0;
    printf("before\n");
    pid = fork();
    if (pid < 0)
    {
        return -1;
    }
    else if (pid == 0)
    {
        printf("hello\n");
    }
    else
    {
        sleep(1);
    }
    printf("after\n");
    
    return 0;
}

这个例子输出的是:

再看个例子:

#include <iostream>
#include <cstdlib>
#include <unistd.h>
using namespace std;

int main()
{
    pid_t pid = 0;
    printf("before\n");
    pid = fork();
    if (pid < 0)
    {
        return -1;
    }
    else if (pid == 0)
    {
        printf("hello\n");
        exit(0);
    }
    else
    {
        sleep(1);
    }
    printf("after\n");
    
    return 0;
}

输出如下图:

猜你喜欢

转载自www.cnblogs.com/jobshunter/p/10984650.html