技术的微光 2022-05-16 18:52
浏览 2
已结题

如何让子进程缓存信息不要parent中也打印

问题遇到的现象和发生背景

编写了两个简单程序file1.c和file2.c,file1中通过控制台输出一句信息,file2创建子进程调用file1,要如何才能避免file1的输出信息输出两次呢?

问题相关代码,请勿粘贴截图

file1.c代码:
#include "stdio.h"
#include "stdlib.h"
#include <unistd.h>

int main()
{
// printf("test file-1 \n");
// fsync(STDOUT_FILENO);
char cstr[] = "12345";
write(STDOUT_FILENO, cstr, sizeof(cstr));
exit(0);
}

file2.c代码:
#include "stdio.h"
#include "stdlib.h"
#include <sys/wait.h>
#include <unistd.h>
int main()
{
pid_t pid;

if (pid = vfork() < 0)
{
    printf("fork error \n");
}       
else if (pid == 0)
{
    if (execl("/home/kongchengbo/testshell/test1.out", "test1.out", (char *)0) < 0)
        printf("excel error \n");
    
    if (waitpid(pid, NULL, 0) < 0)
            printf("waitpid error \n");
}

exit(0);

}

运行结果及报错内容

1234512345
实际打印了两次

我的解答思路和尝试过的方法

怀疑是缓冲区没有冲洗掉,尝试了:
1:file1中,没有用write,修改为:
#include "stdio.h"
#include "stdlib.h"
#include <unistd.h>

int main()
{
printf("test file-1 \n");
fsync(STDOUT_FILENO);
exit(0);
}
测试结果:
test file-1
test file-1

修改缓冲大小为NULL,setbuf(stdout, NULL); 效果也一样的,还是打印两次

我想要达到的结果

子进程里面的内容只打印一次

  • 写回答

0条回答 默认 最新

    报告相同问题?

    问题事件

    • 系统已结题 5月24日
    • 创建了问题 5月16日

    悬赏问题

    • ¥20 有关区间dp的问题求解
    • ¥15 多电路系统共用电源的串扰问题
    • ¥15 slam rangenet++配置
    • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
    • ¥15 对于相关问题的求解与代码
    • ¥15 ubuntu子系统密码忘记
    • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
    • ¥15 保护模式-系统加载-段寄存器
    • ¥15 电脑桌面设定一个区域禁止鼠标操作
    • ¥15 求NPF226060磁芯的详细资料