【问题标题】:try to print one statement after fork in c尝试在 c 中的 fork 之后打印一条语句
【发布时间】:2020-09-27 15:55:50
【问题描述】:

我希望我的输出是

456
123

但我的输出是

456
123
123
int status;
int pid = fork();
if (pid == 0){
    char* s1 = "4 5 6\n";
    printf("%s", s1);
}
wait(&status);
char* s2 = "1 2 3\n";
printf("%s", s2);

【问题讨论】:

  • 你认为fork 能解释这个输出吗?
  • 在第一个 printf 之后使用 fflush(3)。使用strace(1) 了解正在发生的事情
  • 您在父母和孩子中都打印1 2 3
  • 旁注:精度很重要。您的输出不是456...,而是4 5 6 ...

标签: c unix fork system-calls


【解决方案1】:
char* s2 = "1 2 3\n";
printf("%s", s2);

由于此打印发生在任何检查之外,并且由于分叉的进程在发生fork 调用的位置进行处理,因此两个进程都将到达并执行该打印。

如果您只希望它由父打印,则需要手动确保单独检查:

if (pid == 0){  // This block will only be entered by the child process
    char* s1 = "4 5 6\n";
    printf("%s", s1);

} else if (pid > 0) {  // This block will only be entered by the parent process
    wait(&status);
    char* s2 = "1 2 3\n";  
    printf("%s", s2);

} else {
    // Handle errors
}

【讨论】:

    【解决方案2】:

    由于char* s2 = "1 2 3\n"; printf("%s", s2); 被放置在if 语句的主体之外,父进程也将打印"1 2 3\n"

    地点

    char* s2 = "1 2 3\n";
    printf("%s", s2);
    

    或简化

    puts("1 2 3");
    

    (注意:puts() 自动附加换行符)

    if 语句主体内部:

    int status;
    int pid = fork();
    if (pid == 0) {
        puts("4 5 6");
        puts("1 2 3");
    }
    wait(&status);
    

    只让子进程打印"1 2 3\n"


    除此之外:

    如果你只希望你的输出是

    4 5 6
    1 2 3
    

    您不需要使用fork()

    只需使用printf("%s","4 5 6\n1 2 3");

    【讨论】:

    • 你也可以说“放弃你的整个程序,改用printf("456 123");。”
    • @Ctx 你可能在笑,但这确实是我的想法之一,尽管单个参数printf() 很危险。 (好吧,将其转化为答案并不真实)。抱歉,更新说明。但由于这个问题没有解释,我的答案也是如此。
    • “你可能在笑”嘿嘿 ;)
    • @Ctx 我确实试了一下。问题确实应该包括更多细节。我投票关闭。
    猜你喜欢
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    • 2016-01-18
    相关资源
    最近更新 更多