尝试在c中的fork之后打印一个语句

问题描述 投票:-1回答:1

我希望我的输出成为456123但是我的输出是456123123

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);
c unix fork system-calls
1个回答
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
}
© www.soinside.com 2019 - 2024. All rights reserved.