创建写入文件的线程

标签 c linux

我正在学习线程并尝试实现创建线程的代码。线程写入文件。如果线程已创建,则 返回 0 。此处的代码返回 0 但它确实进入函数 write() 但不写入文件。只是为了检查它是否进入函数,我已经放置了一个 printf() 语句。我希望这里的输入应该由命令行获取,但它也不起作用所以为了让它更简单我只写了“ Hello World ”到文件。

这是代码:-

#include<stdio.h> 
#include<stdlib.h>
#include<pthread.h>

void *write(void *arg)
{

    printf("HI \n");
    FILE *fp;
    fp = fopen("file.txt", "a");
    if (fp == NULL) {
        printf("error\n");
    } else {
        fprintf(fp, "hello world");
    }
}

int main()
{
    pthread_t thread;
    int tid;
    tid = pthread_create(&thread, NULL, write, NULL);
    printf("thread1 return %d \n", tid);
    exit(0);
}

最佳答案

我怀疑正在发生的事情是在 fprintf() 将内容放入缓冲区之前执行 exit() 调用。

pthread_create() 在创建线程之后返回,而不是在线程结束之后返回,然后两个线程同时运行。也许这是您的第一个“竞争条件”?

void *result; pthread_join(tid, &result); 将等待在另一个线程中运行的函数返回(并获取它的返回值)。

更正 忘了文件指针不会自动关闭,所以这也会阻碍你。在 fprintf 之后调用 fflush() 或 fclose()。

关于创建写入文件的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18425801/

相关文章:

c - 从代码中断程序中删除 printf 语句

linux - Unix/Linux 文件系统

c++ - nm、objdump 和 pfunct 给出相互矛盾的答案来检查函数是否内联

c - 将自己的库添加到 QT creator C 项目

c - 带有 IDAT 的调色板基础 PNG,其 BTYPE=00 用于无压缩,现在带有 Adler32 代码

c - malloc 有时会失败。或者 pread 有时会失败

Linux文件删除错误

linux - 如何在内核中获取变量的地址?

c - gcov: 无法打开图形文件

c - 需要 API 完整性自动测试帮助