开发者

Wait not working to sync three processes

Im a new C dev. I'm trying to sync three processes to print [FATHER][SON][GRANDSON][FATHER][SON][GRANDSON] with this code:

int main(开发者_高级运维int argc, char **argv)
{

    int c = 0;
    while (c<2)
    {
        c++;
        printf("[FATHER]");
        pid_t son = fork();
        if (son == 0)
        {
            printf("[SON]");
            pid_t grandson = fork();
            if (grandson == 0)
            {
                printf("[GRANDSON]");
                return 0;
            }
            wait(NULL);
            return 0;
        }
        wait(NULL);
    };

  }

Instead, im getting this output: [FATHER][SON][GRANDSON][FATHER][SON][FATHER][FATHER][SON][GRANDSON][FATHER][FATHER][SON][FATHER][FATHER]

Am i misunderstanding or missing something when using wait on code? Thank you very very much.


Instead of calling fflush after every call to printf, it'd be better if you used the write system call to print to stdout (format the output string using sprintf first if necessary). The write system call does unbuffered writing, which would prevent you from having to remember to call fflush every time.

You could even use a variadic macro to avoid writing always a sprintf line followed by a write line.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜