execl拷贝图片

1:拷贝图片

复制代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, const char *argv[])
{
    //在子进程拥有和父进程一样的拷贝文件(确保拷贝文件为空)
    int fp_w =  open("cpy.jpg",O_WRONLY|O_CREAT|O_TRUNC,0664);
    if(fp_w<0)
    {
        perror("open");
        return -1;
    }
    //关闭创建的拷贝文件
    close(fp_w);
    //创建一个子进程
    pid_t pid = fork();
    //在父进程中打开原文件和拷贝文件
    int fp_r = open("photo1.jpg",O_RDONLY);
    if(fp_r<0)
    {
        perror("open");
        return -1;
    }
    fp_w=open("cpy.jpg",O_WRONLY);
    if(fp_w<0)
    {
        perror("open");
        return -1;
    }
    //计算原文件大小,并返回字节大小
    off_t size = lseek(fp_r,0,SEEK_END);
    //pid>0进入父进程
    if(pid>0)
    {                                                               
        //让原文件和目标文件都偏移到起始位置
        lseek(fp_r,0,SEEK_SET);
        lseek(fp_w,0,SEEK_SET);

        char c;
        //一个字节一个字节循环拷贝,且只拷贝一半
        for(int i=0;i<size/2;i++)
        {
            read(fp_r,&c,1);

            write(fp_w,&c,1);
        }
        printf("前半部分拷贝完成!\n");
    }
    //进入子进程
    else if(pid == 0)
    {
        execl("./cp2out","./cp2out",NULL);

    }
    else 
    {
        perror("fork");
        return -1;
    }
    close(fp_w);
    close(fp_r);

return 0;
}

结果图片:

2:数组的翻转

复制代码
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

static char buf[] = "1234567";
void* callBack(void* arg)
{
    int len = strlen(buf);
    for(int i=0 ;i<len;i++)
    {
        printf("%c",buf[i]);
    }
    putchar(10);
    return NULL;
}
void* callBack1(void* arg)
{
    int len = strlen(buf);
    for(int i=0;i<len/2;i++)
    {
        buf[i] = buf[i] ^ buf[len-1-i];
        buf[len-1-i] = buf[i] ^ buf[len-1-i];
        buf[i] = buf[i] ^ buf[len-1-i];
    }
//  for(int i=0;i<len;i++)
//  {
//      printf("%c",buf[i]);
//  }
//  putchar(10);
}
                                                    

int main(int argc, const char *argv[])
{   
    pthread_t A;
    pthread_t B;
    if(pthread_create(&A,NULL,callBack1,NULL)!=0)
    {
        perror("pthread_create ");
        return -1;
    }
    if(pthread_create(&B,NULL,callBack,NULL)!=0)
    {   
        perror("pthread_create ");
        return -1;
    
    }
    
    pthread_join(B,NULL);
    pthread_join(A,NULL);

    return 0;
}
相关推荐
小O的算法实验室7 小时前
IEEE TASE,基于MPC的多无人机协同搜索竞争群体优化方法
算法
Tbisnic8 小时前
BGE-M3 算法详解:从模型架构到三种检索方式的数学原理
算法·自然语言处理·大模型·bert·transformer·注意力机制
Brilliantwxx8 小时前
【算法从零到千】【55-58】哈希位图+常见数学运算 接口
算法
空堂与归9 小时前
用户分群找不到规律?用K-Means聚类算法自动发现数据模式
算法·机器学习·kmeans·聚类
动词ing9 小时前
【C语言】自定义函数+指针入门
c语言·开发语言·算法
重生之后端学习10 小时前
283. 移动零[简单]✅
开发语言·数据结构·算法·leetcode·职场和发展
一只小小的芙厨10 小时前
基础数论总结
笔记·学习·算法
夜不会漫长12 小时前
C++入门(1)
开发语言·c++·算法
wen_zhufeng12 小时前
IndexTTS 2.5 技术报告
人工智能·算法·机器学习
大熊背13 小时前
树莓派相机自动白平衡详解(四)
算法·树莓派·白平衡·isppipeline