DAY 5


    int flag = 0;

void* task(void* arg){
    puts("child thread start");
    while(!flag){
        puts("child thread sleeping...");
        sleep(1);
    }
    int fd = *(int *)arg;
    char buf[64] = {};
    lseek(fd, 0, SEEK_SET);
    int ret = read(fd, buf, sizeof(buf));
    printf("child thread read %d byte(s): %s\n", ret, buf);
    puts("child thread end");
    return NULL;
}
void getLine(char* buf){
    char ret, i = 0;
    while((ret = fgetc(stdin)) != EOF && ret != '\n')
        buf[i++] = ret;
}


int main(int argc, const char *argv[])
{
    puts("main thread start");

    int fd = open(argv[1], O_CREAT|O_RDWR|O_TRUNC, S_IRWXU);
    if(-1 == fd){
        perror("open");
        return 1;
    }

    pthread_t tid;
    int ret = pthread_create(&tid, NULL, task, &fd);
    if(ret){
        perror("pthread create");
        return 1;
    }

    char buf[64] = {};
    getLine(buf);
    while(flag);
    ret = write(fd, buf, strlen(buf));
    flag = 1;
    printf("write %d byte(s)\n", ret);


    puts("main thread wait for child thread to join...");
    pthread_join(tid, NULL);
    close(fd);
    puts("main thread end");
    return 0;
}

                                                                                   
                                                                                   
                                                                                   
                                                                                   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值