在 C 中使用 fork() 和 write() 打印行为

  • 本文关键字:write 打印 fork c fork
  • 更新时间 :
  • 英文 :


在下面的程序中,调用了一个fork()并创建了一个子级。我知道在使用缓冲输出(如 printf() 中时会出现不可预测的输出。为了解决这个问题,我正在使用未缓冲的 write()。

问题是 write() 没有将 与字符串一起打印。

我尝试使用 setvbuf() 禁用缓冲标准输出,就像其他帖子建议的那样,我也尝试使用 fflush(stdout)。但输出总是相同的。

当我将输出重定向到这样的文件

./main.out > output.txt

输出看起来不错。我知道这是有效的,因为在将输出重定向到文件时,系统通过缓冲整个输出而不仅仅是行缓冲来做到这一点。

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#define NO_ERROR 0
#define BUFFER_SIZE 50
void childProcess();
void parentProcess();
int main(int argc, char * argv[])
{
int pid = (int) fork();
if(pid < 0)
{
puts("Error: Fork process failed");
}
else if (pid == 0)
{
childProcess();
}
else
{
parentProcess();
}
return NO_ERROR;
}

void childProcess()
{
char buffer[BUFFER_SIZE];
int pid = (int) getpid();
sprintf(buffer, "This line is from Child pid %dn", pid);
write(1, buffer, strlen(buffer));
}
void parentProcess()
{
char buffer[BUFFER_SIZE];
int pid = (int) getpid();
sprintf(buffer, "This line is from Parent pid %dn", pid);
write(1, buffer, strlen(buffer));
}

Cygwin 中的输出如下所示:(输出后还打印 1 或 2 行新行)

This line is from Parent pid 20016This line is from Child pid 11784

预期产出:

This line is from Parent pid 20016
This line is from Child pid 11784

在另一台运行 Linux 的机器上测试。输出看起来不同,但仍然不如预期。第二行在提示后打印。

user@server$ ./main.out
This line is from Parent pid 31599
user@server$ This line is from Child pid 31600

你的两个进程不同步,这意味着父子同时运行。在这种情况下,输出是不可预测的。例如,您可以使用wait()函数让父亲等待儿子的结束。

void parentProcess(void)
{
wait(NULL);  // father is sleeping until his son dies
char buffer[BUFFER_SIZE];
int pid = (int) getpid();
sprintf(buffer, "This line is from Parent pid %dn", pid);
write(1, buffer, strlen(buffer));
}

最新更新