我使用fork()来运行不同的proccesses并打印一条简单的消息。代码的结果虽然对我有所帮助。看看代码:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <math.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <time.h>
int main(void)
{
fork();
fork();
fork();
fprintf(stderr,"hello world\n");
}
,输出为:
mario@ubuntu:~/OS$ ./main
hello world
hello world
hello world
hello world
hello world
hello world
mario@ubuntu:~/OS$ hello world
hello world
mario@ubuntu:~/OS$
请注意,我在终端的第一行执行程序,但输出不是我所期望的。请帮我!提前致谢!如果用printf(“......”)
更改fprintf,也会发生同样的事情 编辑:我不明白为什么印刷品是这样的。在终点线旁边有六个,在它旁边有1个......之后......答案 0 :(得分:3)
当父程序退出时,运行父程序的shell在屏幕上打印了shell提示符mario@ubuntu:~/OS$
。在提示之后,将打印任何未打印出hello world
的子程序。如果您希望提示不在所有hello world
之前出现,则需要让父母等待所有子节点和孙子节目终止。
检查this以了解如何让父母等待。
答案 1 :(得分:0)
您正在创建8个进程。每个fork
将流程分为两个。原始父级完成了我仍在执行的其他进程。因此,如果原始进程完成执行,则获取一个go并打印提示,尽管其他进程仍在执行。