linux中fork()和vfork()函数的使用和区别

linux中fork()和vfork()函数的使用和区别


fork()的使用如下:


</pre><pre name="code" class="cpp">#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int glob = 6;
char buf[] = "a write to stdout\n";

int main()
{
    int var;
    pid_t pid;
    FILE *fp = NULL;
    fp=fopen("./1.log", "aw");
    fwrite(buf, sizeof(buf), 1, fp);
    pid = fork();
    if(pid < 0)
        printf("err\n");
    if(pid == 0)
    {
        glob++;
        printf("child: %d\n", glob);
    }
    else
    {
        sleep(3);
        printf("parent: %d\n", glob);
    }
    fclose(fp);
    exit(0);
}
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">由于fork使子进程不继承父进程的资源,所以,在子进程中改变glob的值,并不影响,父进程的glob的值</span>

输出结果时在1.log中出现两行buf的文字


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

int glod = 6;
char buf[] = "a write to stdout\n";

int main()
{
    pid_t pid;
    FILE *fp = NULL;
    fp=fopen("./1.log", "aw");
    fwrite(buf, sizeof(buf), 1, fp);
    pid = vfork();
    if(pid< 0)
    {
        printf("err.\n");
    }
    if(pid == 0)
    {
        glod++;
        printf("child: %d\n", glod);
//      _exit(0);
        exit(0);
    }
    else
    {
        printf("parent: %d\n", glod);
    }
    exit(0);
}

在子进程中改变glod值,父进程也随之改变

1.log中只出现一行buf内容


猜你喜欢

转载自blog.csdn.net/ainiding222/article/details/42774405
今日推荐