简体   繁体   English

C fork程序说明

[英]C fork program explanation

I have a code as below 我有一个代码如下

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    printf("a\n");
    fork();

    printf("b\n");
    if(fork() == 0) {
        printf("c\n");
        exit(0);    
    }
    printf("d\n");
    return 0;
}

Output : 输出:

a
b
d
a
b
c
a
b
d
a
b
c

I don't know why the output duplicated many times. 我不知道为什么输出重复多次。

I don't know why the output duplicated many times 我不知道为什么输出重复多次

Because printf() is buffered. 因为printf()是缓冲的。

When a process calls fork() , the resulting child process obtains a copy of the parent's output buffer. 当进程调用fork() ,生成的子进程将获取父进程缓冲区的副本。

You can empty this output buffer by placing fflush(stdout) just before each call to fork() . 您可以在每次调用fork()之前放置fflush(stdout)来清空此输出缓冲区。 In that case output should be: 在这种情况下,输出应该是:

a
b
b
d
c
d
c

Note that if the output refered to a terminal, it would be line-buffered by default, ie: the buffer would be dumped every time a \\n is sent to the output. 请注意,如果输出引用到终端,则默认情况下它将是行缓冲的,即:每次将\\n发送到输出时,都会转储缓冲区。 Not so if you are redirecting the output to a file. 如果要将输出重定向到文件,则不是这样。

When you call fork() it gets a copy of output buffer of the calling process. 当你调用fork()它会获得调用进程的输出缓冲区的副本。 Buffering is enabled by default, so you get this behavior. 默认情况下启用缓冲,因此您会收到此行为。 You can use 您可以使用

fflush(stdout);

before a call to fork(). 在调用fork()之前。 Or, you can also disable buffering using 或者,您也可以使用禁用缓冲

setbuf(stdout, NULL);

You can read more about fork here . 你可以在这里阅读更多关于fork的内容 Let me know if you need any more help. 如果您需要更多帮助,请与我们联系。

The answer is already in the comments. 答案已在评论中。 You are calling fork() twice. 你正在调用fork()两次。 So the solution is to just call it once and save the result in a variable like this int pid = fork() . 因此解决方案是只调用一次并将结果保存在一个变量中,如int pid = fork() Also, you should check if the fork-call failed (if it does, it returns a negative value). 此外,您应该检查fork-call是否失败(如果是,则返回负值)。

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    printf("a\n");

    int pid = fork();
    if (pid < 0)
    {
        fprintf(stderr, "Can't fork!");
        exit(1);
    }

    printf("b\n");

    if(pid == 0)
    {
        printf("c\n");
    }
    else
    {
        printf("d\n");
    }

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM