#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
int id=atoi(argv[0]);
int cpid=atoi(argv[1]);
off_t size=atoi(argv[2]);
sleep(3);
lseek(id,0,SEEK_SET);
lseek(cpid,0,SEEK_SET);
char a;
for(int i=0;i<size/2;i++)
{
read(id,&a,1);
write(cpid,&a,1);
}
printf("前半部分拷贝完成\n");
close(id);
close(cpid);
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
int id;
id=open("1.png",O_RDONLY);
if(id<0)
{
perror("open");
return -1;
}
int cpid;
cpid=open("cpy.png",O_WRONLY|O_CREAT|O_TRUNC,0664);
if(id<0)
{
perror("open");
return -1;
}
off_t size=lseek(id,0,SEEK_END);
pid_t pid;
pid=fork();
if(pid>0)
{
char ar1[10];
sprintf(ar1,"%d",id);
char ar2[10];
sprintf(ar2,"%d",cpid);
char ar3[10];
sprintf(ar3,"%ld",size);
execl("exex",ar1,ar2,ar3,NULL);
}
else if(pid==0)
{
lseek(id,size/2,SEEK_SET);
lseek(cpid,size/2,SEEK_SET);
char a;
for(int i=0;i<size/2+1;i++)
{
read(id,&a,1);
write(cpid,&a,1);
}
printf("后半部分拷贝完成\n");
}
else
{
perror("fork");
return -1;
}
close(id);
close(cpid);
return 0;
}
运行结果
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
char buff[]="1234567";
// 原地倒置字符串的函数
void string1(char *str, int length)
{
char temp;
for (int i = 0; i < length / 2; i++)
{
temp = str[i];
str[i] = str[length - 1 - i];
str[length-1-i] = temp;
}
}
//A线程
void *ballka(void *pa)
{
/*
for(int i=0;i<7;i++)
{
printf("%c",buff[i]);
}
*/
while(1)
{
printf("%s\n",buff);
sleep(1);
}
printf("this is A线程\n");
return NULL;
}
//B线程
void *ballkb(void *pa)
{
while(1)
{
string1(buff,strlen(buff));
sleep(2);
}printf("this is B\n");
return NULL;
}
int main(int argc, const char *argv[])
{
//线程a
pthread_t tid;
if(pthread_create(&tid,NULL,ballka,NULL)!=0)
{
printf("pthread_create shibai\n");
return -1;
}
//线程B
pthread_t tid1;
if(pthread_create(&tid1,NULL,ballkb,NULL)!=0)
{
printf("pthread_create shibai\n");
return -1;
}
while(1)
sleep(1);
// pthread_join(tid1,NULL);
// pthread_join(tid,NULL);
return 0;
}
错误原因:
A线程可能在B线程倒置字符串的过程中打印出其他字符串。执行多次后,打印的顺序可能会乱。