C fork调用中的奇怪输出 [英] Weird output in C fork call

查看:68
本文介绍了C fork调用中的奇怪输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下C代码.

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


int main ()
{

    int i=1;

    pid_t child_pid = fork();

    if (child_pid == 0) 
    {
        printf ("%d\n", i++);
        printf ("%d\n", i++);
        printf ("This is child process.");
        return 0;


    }
    else if (child_pid > 0) {
        printf ("%d\n", i++);
        printf ("This is parent process.");
    }

    else {
    printf("Fork failed");
    }

}

我编译如下:gcc testFork.c并通过键入./a.out来运行代码.

I compiled the following as follows: gcc testFork.c and ran the code by typing ./a.out.

我得到的输出是:

vmw_ubuntu@vmwubuntu:~/Desktop/Test C$ ./a.out
1
This is parent process.vmw_ubuntu@vmwubuntu:~/Desktop/Test C$ 1
2
This is child process.

为什么vmw_ubuntu@vmwubuntu:~/Desktop/Test C$出现在茫茫荒野之中?

Why is vmw_ubuntu@vmwubuntu:~/Desktop/Test C$ appearing in the middle of nowhere?

我只是希望得到以下输出:

I am simply expecting this output:

vmw_ubuntu@vmwubuntu:~/Desktop/Test C$ ./a.out
1
This is parent process.1
2
This is child process.

推荐答案

因为您没有在printf调用的末尾添加换行符'\ n'转义字符;因此,当您的父进程返回到您的外壳程序时,外壳程序"vmw_ubuntu @ vmwubuntu:〜/Desktop/Test C $"的提示会附加到末尾.

Because you didn't add a newline '\n' escape character at the end of your printf call; and thus, when your parent process returned to your shell, the prompt of your shell `vmw_ubuntu@vmwubuntu:~/Desktop/Test C$' was appended to the end.

请记住,当您调用"fork"时,您将为同一过程创建2个单独的副本.它不再是1个程序,父级可以在子级之前返回.

Remember that when you call 'fork' you're creating 2 separate copies of the same process. It's no longer 1 program, and the parent can return before the child.

要获得所需的输出,您需要插入对"waitpid"函数的调用.参见 http://linux.die.net/man/2/wait

To achieve the output you want, you need to insert a call to the 'waitpid' function. see http://linux.die.net/man/2/wait

这篇关于C fork调用中的奇怪输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆